4 Replies
Latest reply on May 28, 2017 1:46 PM by John368
Level 1 (0 points)

Please tell a command, or a function, or a subscript, or a property with which I can sum the values of an array

For example, there is array

```var arrayPoint = [1, 3, 12]
```

I want to get a sum of values

1 + 3 + 12

• ###### Re: Totalization of array values
Level 8 (8,095 points)

There is the built in reduce function for this :

let sum = arrayPoint.reduce(0, combine: +)

If you want the product :

You have other interesting functions on collections (map, filter, reduce); look  here

h ttps://useyourloaf.com/blog/swift-guide-to-map-filter-reduce/

1 of 1 people found this helpful
• ###### Re: Totalization of array values
Level 1 (0 points)

Thank you for the function and link

• ###### Re: Totalization of array values
Level 2 (40 points)

Hi,

The shortest, best and standard Swift way is using reduce:

```
var arrayPoint = [1, 3, 12]
let arraySum = arrayPoint.reduce(0,+)
print(arraySum)

```

But if you want to have some fun and create your own code, this is a really nice case to create yourself a recursive function:

```
func sumArray(_ numbers: [Int]) -> Int {
var sumTheseNumbers = numbers
if sumTheseNumbers.count <= 0 {
return 0
} else {
let firstNumber = sumTheseNumbers.removeFirst()
return  firstNumber + sumArray(sumTheseNumbers)
}
}
var arrayPoint = [1, 3, 12]
let theSum = sumArray(arrayPoint)
print(theSum)
```

Have fun,

Joris

1 of 1 people found this helpful
• ###### Re: Totalization of array values
Level 1 (0 points)

Thank you for the example of code