Last active
February 14, 2020 10:22
-
-
Save danhalliday/a2f095649222ec037cb5968e70944002 to your computer and use it in GitHub Desktop.
Sum Swift extension, including sum by property.
This file contains 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 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