Skip to content

Instantly share code, notes, and snippets.

@Sajjon
Forked from natecook1000/comparable-keypaths.swift
Created September 3, 2018 09:41
Show Gist options
  • Save Sajjon/b51bf49cf844893baf789fb815c969bc to your computer and use it in GitHub Desktop.
Save Sajjon/b51bf49cf844893baf789fb815c969bc 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