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
Was this helpful?