Skip to content

Instantly share code, notes, and snippets.

@azonov
Created November 18, 2019 10:30
Show Gist options
  • Save azonov/48fddc72663391ff5e44c77028f7a661 to your computer and use it in GitHub Desktop.
Save azonov/48fddc72663391ff5e44c77028f7a661 to your computer and use it in GitHub Desktop.
extension Sequence {
public func sortedAscending<T: Comparable>(by keyPath: KeyPath<Element, T>) -> [Element] {
sorted(by: keyPath, comparator: <)
}
public func sortedDescending<T: Comparable>(by keyPath: KeyPath<Element, T>) -> [Element] {
sorted(by: keyPath, comparator: >)
}
public func sorted<T: Comparable>(by keyPath: KeyPath<Element, T>, comparator: (T, T) -> Bool) -> [Element] {
sorted { comparator($0[keyPath: keyPath], $1[keyPath: keyPath]) }
}
}
extension Array {
@inlinable public mutating func sortedAscending<T: Comparable>(by keyPath: KeyPath<Element, T>) {
sort(by: keyPath, comparator: <)
}
@inlinable public mutating func sortedDescending<T: Comparable>(by keyPath: KeyPath<Element, T>) {
sort(by: keyPath, comparator: >)
}
@inlinable public mutating func sort<T: Comparable>(by keyPath: KeyPath<Element, T>, comparator: (T, T) -> Bool) {
sort { comparator($0[keyPath: keyPath], $1[keyPath: keyPath]) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment