Skip to content

Instantly share code, notes, and snippets.

@samdods
Last active October 3, 2018 09:51
Show Gist options
  • Save samdods/ad89570a53d02ce103027f35b21fc8ad to your computer and use it in GitHub Desktop.
Save samdods/ad89570a53d02ce103027f35b21fc8ad to your computer and use it in GitHub Desktop.
prefix operator ~
prefix func ~<A, B>(_ keyPath: KeyPath<A, B>) -> (A) -> B {
return { $0[keyPath: keyPath] }
}
// list of names for each person
people.map(~\.name)
// => ["Tom", "Dick", "Harry", "Alice", "Bob", "Charles"]
// list of cities for each person
people.map(~\.address.city)
// => ["London", "Nottingham", "London", "Edinburgh", "Nottingham", "Leicester"]
// list of IDs for each person's address, where present
people.compactMap(~\.address.id)
// => ["1b0d", "0xg2"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment