对 swift 中的通用集进行排序
Sorting generic set in swift
在 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 版测试版 (7B60),这是 swifts Set
类型的包装器。
items.sort{[=14=] < }
无效
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{[=12=] < }
$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 中对通用类型集进行排序的正确方法是什么?
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 版测试版 (7B60),这是 swifts Set
类型的包装器。
items.sort{[=14=] < }
无效
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{[=12=] < }
$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。