Created
April 13, 2020 16:31
-
-
Save KanshuYokoo/7baf8766cb9ecd72c1e6eab0d8f24fe6 to your computer and use it in GitHub Desktop.
utilities with swift keypath, sorting, map, min, max
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
extension Sequence { | |
func sorted<T: Comparable>(by keyPath:KeyPath<Element, T>) -> [Element]{ | |
return sorted {a, b in | |
return a[keyPath: keyPath] < b[keyPath:keyPath] | |
} | |
} | |
func map <T> (_ keyPath: KeyPath<Element, T>) -> [T] { | |
return map {$0[keyPath: keyPath]} | |
} | |
func min <T: Comparable> (_ keyPath: KeyPath<Element, T>) -> T? { | |
return map(keyPath).min() | |
} | |
func max<T: Comparable> (_ keyPath: KeyPath<Element, T>) -> T? { | |
return map(keyPath).max() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment