Skip to content

Instantly share code, notes, and snippets.

@samdods
Last active October 3, 2018 08:12
Show Gist options
  • Save samdods/9d9a91c4e7926444fa684b2231b39233 to your computer and use it in GitHub Desktop.
Save samdods/9d9a91c4e7926444fa684b2231b39233 to your computer and use it in GitHub Desktop.
prefix func ~<A, B>(_ keyPath: KeyPath<A, B>) -> (A, A) -> Bool where B: Comparable {
return { $0[keyPath: keyPath] < $1[keyPath: keyPath] }
}
// sort in situ, by name
var p2 = people
p2.sort(by: ~\.name)
// people sorted by name
people.sorted(by: ~\.name)
// people sorted by name in reverse order
people.sorted(by: ~\.name).reversed()
// people sorted by their address city
people.sorted(by: ~\.address.city)
// the names of the people sorted by name
people.sorted(by: ~\.name).map(~\.name)
// => ["Alice", "Bob", "Charles", "Dick", "Harry", "Tom"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment