Skip to content

Instantly share code, notes, and snippets.

@thexande
Created August 19, 2019 02:32
Show Gist options
  • Save thexande/50ea68c60a5d45891dc7078e70e1a07f to your computer and use it in GitHub Desktop.
Save thexande/50ea68c60a5d45891dc7078e70e1a07f to your computer and use it in GitHub Desktop.
Extend map to support mapping to object key paths.
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