Sort `Collection` using `KeyPath`

This is a great idea! I have been using something very similar to this, except with a closure that takes a comparator instead of just a value.

extension Collection{
    func sorted<Value: Comparable>(
        by keyPath: KeyPath<Element, Value>,
        _ comparator: (_ lhs: Value, _ rhs: Value)->Bool)->[Element]{
        return self.sorted{
            comparator($0[keyPath: keyPath], $1[keyPath: keyPath])
        }
    }
}

https://pbs.twimg.com/media/DWDX0hUV4AAZc2W?format=jpg&name=small

5 Likes