Created
May 22, 2018 14:18
-
-
Save natecook1000/f1a698f67474e207767a30519d1c9251 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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