Skip to content

Instantly share code, notes, and snippets.

@samdods
Created October 2, 2018 20:05
Show Gist options
  • Save samdods/00d6a14a6430d824281822fdc2419672 to your computer and use it in GitHub Desktop.
Save samdods/00d6a14a6430d824281822fdc2419672 to your computer and use it in GitHub Desktop.
/// Prefix operator to turn a KeyPath into a function
prefix operator ~
/// Allows a key path to be passed into mapping functions
///
/// e.g. people.map(~\.name)
///
prefix func ~<A, B>(_ keyPath: KeyPath<A, B>) -> (A) -> B {
return { $0[keyPath: keyPath] }
}
/// Allows a key path to be passed into sorting functions
///
/// e.g. people.sorted(~\.name)
///
prefix func ~<A, B>(_ keyPath: KeyPath<A, B>) -> (A, A) -> Bool where B: Comparable {
return { $0[keyPath: keyPath] < $1[keyPath: keyPath] }
}
/// Allows a Boolean-type key path to be passed into filter-like functions,
/// `filter`, `first(where:)`, `drop(while:)`, etc.
///
/// e.g. people.first(where: ~\.address.street.isEmpty)
///
prefix func ~<A>(_ keyPath: KeyPath<A, Bool>) -> (A) -> Bool {
return { $0[keyPath: keyPath] }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment