Skip to content

Instantly share code, notes, and snippets.

@khanlou
Created September 24, 2020 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khanlou/6aa619dca1399611bdbfb69739dd0987 to your computer and use it in GitHub Desktop.
Save khanlou/6aa619dca1399611bdbfb69739dd0987 to your computer and use it in GitHub Desktop.
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