Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@duemunk
Last active August 2, 2019 12:05
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duemunk/fde2908c1810e2ebbd40bd62efeb59c6 to your computer and use it in GitHub Desktop.
Save duemunk/fde2908c1810e2ebbd40bd62efeb59c6 to your computer and use it in GitHub Desktop.
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"]
@ibrahimkteish
Copy link

Shorter version

let firstnames = persons.map(\.firstname) // ["Tobias", "John", "Jane"]
let lastnames = persons.flatMap(\.lastname) // ["Due Munk", "Doe"]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment