import Foundation
Sequence 协议的一个便捷扩展,允许你以 Swift 风格的方式对元素进行排序。它受到 iOS >= 15 中 SortDescriptor 实现以及 Swift by Sundell 文章关于排序 Swift 集合的启发。如果你的项目的最低目标操作系统版本是 iOS >= 15,你应该使用 Apple 专有的 SortDescriptor。
struct SomeSortableStructure {
let id: Int
let isSelected: Bool
let title: String
let description: String?
}
struct SorterGuy {
func sort(_ items: [SomeSortableStructure]) -> [SomeSortableStructure] {
items.sorted(using: [
.keyPath(\.title, order: .ascending),
.keyPath(\.isSelected, order: .descending),
.keyPath(\.description, order: .ascending),
.keyPath(\.id, order: .ascending)
])
}
}
该实现非常简洁,因此在大多数情况下,可以直接复制到目标项目。
dependencies: [
.package(url: "https://github.com/Hydralo/SwiftKeyPathSortingRetrofit.git")
]