在 swift 中对泛型类型集进行排序的正确方法是什么?
class CustomSet<T: Hashable>: NSObject {
var items: Set<T>
init(_ items: [T]) {
self.items = Set(items)
}
var toSortedArray: [T] {
//Error: Binary operator '<' cannot be applied to two 'T' operands
return items.sort{ (a: T, b: T) -> Bool in return a < b}
}
}
Xcode 版本 7.1 beta (7B60),这是 swifts 的包装器 Set
类型。
items.sort{$0 < $1}
不起作用
Cannot invoke 'sort' with an argument list of type '((_, _) -> _)'
.
但适用于 xcrun swift
1> let s = Set([4,2,3,4,6])
s: Set<Int> = {
[0] = 6
[1] = 2
[2] = 4
[3] = 3
}
2> s.sort{$0 < $1}
$R0: [Int] = 4 values {
[0] = 2
[1] = 3
[2] = 4
[3] = 6
}
最佳答案
您需要限制您的通用占位符以符合 Comparable (以及 Hashable,您已经在这样做)。否则,正如错误消息所示,我们不能保证 <
是适用的。
class CustomSet<T: Hashable where T:Comparable>: NSObject {
您的xcrun
示例之所以有效,是因为 Int 确实符合 Comparable。
关于swift - 快速排序泛型集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36096630/