我知道 Swift 中泛型的局限性以及它们存在的原因,所以这不是关于编译器错误的问题。相反,我偶尔会遇到一些情况,似乎它们应该可以通过某些可用资源(即泛型、关联类型/协议等)的组合来实现,但似乎无法找到解决方案。
在这个例子中,我试图用 Swift 替代 NSSortDescriptor(只是为了好玩)。当您只有一个描述符时,它可以完美运行,但是就像 NS 版本通常所做的那样,创建一个 SortDescriptors 数组来对多个键进行排序会很好。
这里的另一个试验是使用 Swift KeyPaths。因为那些需要一个 Value 类型,而比较需要一个 Comparable 值,所以我在弄清楚在哪里/如何定义满足所有要求的类型时遇到了麻烦。
这可能吗?这是我提出的最接近的解决方案之一,但是,正如您在底部看到的那样,它在构建数组时不足。
同样,我理解为什么这不能按原样工作,但我很好奇是否有办法实现所需的功能。
struct Person {
let name : String
let age : Int
}
struct SortDescriptor<T, V:Comparable> {
let keyPath: KeyPath<T,V>
let ascending : Bool
init(_ keyPath: KeyPath<T,V>, ascending:Bool = true) {
self.keyPath = keyPath
self.ascending = ascending
}
func compare(obj:T, other:T) -> Bool {
let v1 = obj[keyPath: keyPath]
let v2 = other[keyPath: keyPath]
return ascending ? v1 < v2 : v2 < v1
}
}
let jim = Person(name: "Jim", age: 30)
let bob = Person(name: "Bob", age: 35)
let older = SortDescriptor(\Person.age).compare(obj: jim, other: bob) // true
// Heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional
var descriptors = [SortDescriptor(\Person.age), SortDescriptor(\Person.name)]