sort using key paths

// โญ๏ธ custom sorting using key paths
extension Sequence {
    func sorted<T: Comparable>(
        by    keyPath: KeyPath<Element, T>,
        // โญ๏ธ in ascending order by default.
        using compare: (T, T) -> Bool = (<)    // โญ๏ธ ้ ่จญ้‹็ฎ—(ๆ‹ฌ่™Ÿ็‚บๅฟ…่ฆ)
    ) -> [Element] {
        sorted { a, b in
            compare(a[keyPath: keyPath], b[keyPath: keyPath])
        }
    }
}

todolist.sorted(by: \.date)
todolist.sorted(by: \.item).map(\.item)
todolist.sorted(by: \.item, using: >).map(\.item)  // descending order

Last updated