Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
extension Sequence {
func sum<T>(_ transform: (Element) -> T) -> T where T: AdditiveArithmetic {
var sum = T.zero
for element in self {
sum += transform(element)
}
return sum
}
}
extension Sequence where Element: AdditiveArithmetic {
func sum() -> Element {
return sum { $0 }
}
}
struct House {
let occupants: Int
}
let houses = [
House(occupants: 3),
House(occupants: 13),
House(occupants: 5),
House(occupants: 1),
]
print(houses.sum { $0.occupants })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment