seq.sorted(_:)
sort a sequence on multiple properties
Last updated
Was this helpful?
sort a sequence on multiple properties
Last updated
Was this helpful?
Was this helpful?
有了下面的擴充後,我們就可以用這麼漂亮的語法來對物件排序:
let sorted = items.sorted(
.descending(\.price),
.descending(\.rate),
.ascending (\.title)
)
👉 replit
// 1.0.0: 2021.12.11
/*
設計理念:
--------
我們將要用於排序的屬性 key path (`prop`) 傳入 `SortOrder`
的 `isBefore` 與 `isEqual` 兩個 closure 中,如此就可以
直接用 order.isBefore(a, b) 或 order.isEqual(a, b) 來
比較兩個 Element 的大小,而不需要為了要將這個 key path 存起來
而傷腦筋到底要用: KeyPath<Element, Property> 還是要用
PartialKeyPath<Element> 型別?
事實上,用這兩種型別存起來都有問題。
contacts.sorted(by: .ascending(\.lastName), .descending(\.age))