我正在尝试将包含 KeyPath 和排序顺序类型的多个元组传递给应该进行排序的方法。
我有这个方法:
extension Array {
mutating func sort<T: Comparable>(by criteria: (path: KeyPath<Element, T>, order:OrderType)...) {
criteria.forEach { path, order in
//...
sort { first, second in
order.makeComparator()(
first[keyPath: path],
second[keyPath: path]
)
}
}
}
}
我正在这样使用它:
var posts = BlogPost.examples
posts.sort(by:(path:\.pageViews, order: .asc), (path:\.sessionDuration, order: .desc))
现在,因为pageViews
和sessionDuration
属性都是integers
,这将起作用。
但是如果我想传递两个不同类型的属性(比如String
和Int
),我会收到这个错误:
Key path value type 'Int' cannot be converted to contextual type 'String'
这是其余的代码,但我想不是那么相关:
enum OrderType: String {
case asc
case desc
}
extension OrderType {
func makeComparator<T: Comparable>() -> (T, T) -> Bool {
switch self {
case .asc:
return (<)
case .desc:
return (>)
}
}
}
我应该如何定义排序方法以便它接受异构键路径?