Skip to content

Instantly share code, notes, and snippets.

@KanshuYokoo
Created April 13, 2020 16:31
Show Gist options
  • Save KanshuYokoo/7baf8766cb9ecd72c1e6eab0d8f24fe6 to your computer and use it in GitHub Desktop.
Save KanshuYokoo/7baf8766cb9ecd72c1e6eab0d8f24fe6 to your computer and use it in GitHub Desktop.
utilities with swift keypath, sorting, map, min, max
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