Forked from natecook1000/comparable-keypaths.swift
Created
September 3, 2018 09:41
-
-
Save Sajjon/b51bf49cf844893baf789fb815c969bc 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