Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding sum of elements in Swift array

Tags:

arrays

swift

What is the easiest (best) way to find the sum of an array of integers in swift? I have an array called multiples and I would like to know the sum of the multiples.

like image 815
ejLev Avatar asked Jul 17 '14 04:07

ejLev


1 Answers

This is the easiest/shortest method I can find.

Swift 3 and Swift 4:

let multiples = [...] let sum = multiples.reduce(0, +) print("Sum of Array is : ", sum) 

Swift 2:

let multiples = [...] sum = multiples.reduce(0, combine: +) 

Some more info:

This uses Array's reduce method (documentation here), which allows you to "reduce a collection of elements down to a single value by recursively applying the provided closure". We give it 0 as the initial value, and then, essentially, the closure { $0 + $1 }. Of course, we can simplify that to a single plus sign, because that's how Swift rolls.

like image 99
username tbd Avatar answered Sep 18 '22 17:09

username tbd