Currently working on a on app with a lot of math to compute different statistics I find myself summing different arrays all the time.
Coming from C# I expected some kind of .sum()
method like LINQ has, but there is nothing like that in Swift.
Current state
I currently sum the arrays using .reduce(0,+)
which I do not mind by the code is not that readable
let total = expenses.map({ $0.amount }).reduce(0,+)
Bad imperative code
Another bigger problem than readability is that I encounter code like this from other developers all the time:
var sum = 0
for expense in expenses {
sum = sum + expense.amount
}
This code might come from imperative thinking but it might also come from not knowing how to use .reduce()
which can look like an intimidating method. A .sum()
would be friendlier and much easier to use even to inexperienced developers.
Solution
My proposed solution is to introduce a .sum()
method on collections, so
let total = expenses.map({ $0.amount }).reduce(0,+)
can be written as
let total = expenses.map({ $0.amount }).sum()
or even better
let total = expenses.sum({ $0.amount })
Implementation
The actual implementation should be easy, just two extension method on Collection
in the standard library
extension Collection where Element: Numeric {
func sum() -> Element {
return reduce(0, +)
}
}
extension Collection {
func sum<T: Numeric>(_ transform: (Element) throws -> T) rethrows -> T {
return try map(transform).sum()
}
}