Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find sum of all elements in array in swift 4

Tags:

swift

swift4

I have array like this

let arr = [1,2,3,4,5,6,7,8,9,10]

I tried var totalSum = arr.map({$0.points}).reduce(0, +) but not worked

can I find all objects sum value?

like image 352
senthil Avatar asked Dec 07 '22 15:12

senthil


2 Answers

You need to drop the map & points

let arr = [1,2,3,4,5,6,7,8,9,10]

let totalSum = arr.reduce(0, +)

print("totalSum \(totalSum)")
like image 171
Sh_Khan Avatar answered Dec 31 '22 17:12

Sh_Khan


This is the easiest/shortest method to sum of array.

Swift 3,4:

let arrData = [1,2,3,4,5]
sum = arrData.reduce(0, +)

Or

let arraySum = arrData.reduce(0) { $0 + $1 }

Swift 2:

sum = arrData.reduce(0, combine: +)

like image 43
Jogendar Choudhary Avatar answered Dec 31 '22 17:12

Jogendar Choudhary