Created
August 19, 2019 02:32
-
-
Save thexande/50ea68c60a5d45891dc7078e70e1a07f to your computer and use it in GitHub Desktop.
Extend map to support mapping to object key paths.
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 map<T>(_ keyPath: KeyPath<Element, T>) -> [T] { | |
return self.map { | |
$0[keyPath: keyPath] | |
} | |
} | |
} | |
struct Transaction { | |
let amount: Double | |
let originAddress: String | |
} | |
let transactions: [Transaction] = [ | |
.init(amount: 14.53, | |
originAddress: "1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2"), | |
.init(amount: 344.15, | |
originAddress: "3J98t1WpEZ73CNmQviecrnyiWrnqRhWNL") | |
] | |
print(""" | |
💳 Transactions from addresses | |
\(transactions.map(\.originAddress).joined(separator: ", ")) | |
sent funds totaling | |
💵 \(transactions.map(\.amount).reduce(0, +)) | |
""") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment