extension Collection where Element: Numeric {
var sum: Self.Element {
var result: Self.Element = 0
for num in self {
result += num
}
return result
}
}
[1, 2, 3].sum // 6
[2.5, 2.5].sum // 5
@mgmzlm: you might also use the reduce( ) function to (ha ha) reduce the number of lines of code in your extension.
let sum = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].reduce(0, { $0 + $1 })
print(“sum = (sum)”)
1 Like
Got it, thanks!
extension Sequence where Element: Numeric {
var sum: Self.Element { reduce(0) { $0 + $1 } }
}