Reputation: 75
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?
Upvotes: 5
Views: 8787
Reputation: 418
Without using any built in function.
let arr = Array(1...100)
var sum = 0
arr.forEach { (num) in
sum = sum + num
}
Upvotes: 0
Reputation: 3494
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: +)
Upvotes: 3
Reputation: 100503
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)")
Upvotes: 13