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
import Foundation // Date
// todo item
struct TodoItem {
let date: Date
let item: String
}
// todo item samples
let todos = ["eat", "sleep", "play", "relax"]
let now = Date()
let nextyear = now.yearAfter
extension TodoItem {
static let samples = (1...5).map{ _ in
TodoItem(
date: .random(in: now...nextyear),
item: todos.randomElement()!
)
}
}
let todolist = TodoItem.samples
seq.sorted(_:) โญ๏ธ - sort by multiple keypaths
Last updated