Skip to content

Instantly share code, notes, and snippets.

@jakebromberg
Last active January 23, 2018 18:09
Show Gist options
  • Save jakebromberg/b7094854a2b515f7c1cbdec080a590ae to your computer and use it in GitHub Desktop.
Save jakebromberg/b7094854a2b515f7c1cbdec080a590ae to your computer and use it in GitHub Desktop.
extension Sequence {
func sorted<T: Comparable>(by keyPath: KeyPath<Element, T>, comparator: (T, T) -> Bool = { $0 < $1 }) -> [Element] {
return sorted(by: { (e1, e2) -> Bool in
return comparator(e1[keyPath: keyPath], e2[keyPath: keyPath])
})
}
}
let names = ["Alice", "Bob", "Charlie", "Dave"]
assert(names.sorted(by: \.count) == ["Bob", "Dave", "Alice", "Charlie"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment