Last active
August 2, 2019 12:05
-
-
Save duemunk/fde2908c1810e2ebbd40bd62efeb59c6 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 map<T>(_ keyPath: KeyPath<Element, T>) -> [T] { | |
return self.map { | |
$0[keyPath: keyPath] | |
} | |
} | |
func flatMap<T>(_ keyPath: KeyPath<Element, T?>) -> [T] { | |
return self.flatMap { | |
$0[keyPath: keyPath] | |
} | |
} | |
} | |
struct Person { | |
let firstname: String | |
let lastname: String? | |
} | |
let persons = [ | |
Person(firstname: "Tobias", lastname: "Due Munk"), | |
Person(firstname: "John", lastname: "Doe"), | |
Person(firstname: "Jane", lastname: nil) | |
] | |
let firstnames = persons.map(\Person.firstname) // ["Tobias", "John", "Jane"] | |
let lastnames = persons.flatMap(\Person.lastname) // ["Due Munk", "Doe"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Shorter version