Created
September 24, 2020 17:37
-
-
Save khanlou/6aa619dca1399611bdbfb69739dd0987 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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