Skip to content

Instantly share code, notes, and snippets.

@aainaj
Created June 13, 2020 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aainaj/19c7ce0a5798bafab11f41172f7d7136 to your computer and use it in GitHub Desktop.
Save aainaj/19c7ce0a5798bafab11f41172f7d7136 to your computer and use it in GitHub Desktop.
sort by keypath
extension Collection {
func sorted<Value: Comparable>(on property: KeyPath<Element, Value>, by areInIncreasingOrder: (Value, Value) -> Bool) -> [Element] {
return sorted { currentElement, nextElement in
areInIncreasingOrder(currentElement[keyPath: property], nextElement[keyPath: property])
}
}
}
extension MutableCollection where Self: RandomAccessCollection {
mutating func sort<Value: Comparable>(on property: KeyPath<Element, Value>, by order: (Value, Value) throws -> Bool) rethrows {
try sort { try order($0[keyPath: property], $1[keyPath: property]) }
}
}
struct User {
private(set) var name: String
private(set) var age: Int
}
var users = [User(name: "Aaina", age: 10), User(name: "Tia", age: 20), User(name: "Ria", age: 5)]
users.sort(on: \User.age, by: <)
let names = users.map(\.age)
print(names)
// Prints [5, 10, 20]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment