Skip to content

Instantly share code, notes, and snippets.

@danhalliday
Last active February 14, 2020 10:22
Show Gist options
  • Save danhalliday/a2f095649222ec037cb5968e70944002 to your computer and use it in GitHub Desktop.
Save danhalliday/a2f095649222ec037cb5968e70944002 to your computer and use it in GitHub Desktop.
Sum Swift extension, including sum by property.
extension Sequence where Element: AdditiveArithmetic {
func sum() -> Element {
reduce(.zero, +)
}
}
extension Sequence {
func sum<T: AdditiveArithmetic>(_ keyPath: KeyPath<Element, T>) -> T {
map { $0[keyPath: keyPath] }.sum()
}
func compactSum<T: AdditiveArithmetic>(_ keyPath: KeyPath<Element, T?>) -> T {
map { $0[keyPath: keyPath] }.compactMap { $0 }.sum()
}
func sum<T: AdditiveArithmetic>(_ transform: (Element) throws -> T) rethrows -> T {
try map(transform).sum()
}
func compactSum<T: AdditiveArithmetic>(_ transform: (Element) throws -> T?) rethrows -> T {
try map(transform).compactMap( { $0 }).sum()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment