Skip to content

Instantly share code, notes, and snippets.

@natecook1000
Created May 22, 2018 14:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save natecook1000/f1a698f67474e207767a30519d1c9251 to your computer and use it in GitHub Desktop.
Save natecook1000/f1a698f67474e207767a30519d1c9251 to your computer and use it in GitHub Desktop.
/// Returns a binary predicate using the given key path to create an ascending order
/// for elements of type `Root`.
func ascending<Root, Value: Comparable>(_ path: KeyPath<Root, Value>) -> (Root, Root) -> Bool {
return { $0[keyPath: path] < $1[keyPath: path] }
}
/// Returns a binary predicate using the given key path to create a descending order
/// for elements of type `Root`.
func descending<Root, Value: Comparable>(_ path: KeyPath<Root, Value>) -> (Root, Root) -> Bool {
return { $0[keyPath: path] > $1[keyPath: path] }
}
let chrises = ["Pratt", "Hemsworth", "Rock", "Lattner"]
chrises.sorted(by: ascending(\.count)) // ["Rock", "Pratt", "Lattner", "Hemsworth"]
chrises.sorted(by: descending(\.count)) // ["Hemsworth", "Lattner", "Pratt", "Rock"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment