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?
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)")
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: +)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With