Totalization of array values

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

Replies

There is the built in reduce function for this :


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


You start with 0 (or any other value you want) and add all items in array.


If you want the product :

prod = arrayPoint.reduce(1,combine: *) // Here, need to start with 1


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


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

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

Thank you for the function and link

Thank you for the example of code