在swift中对通用集进行排序

时间:2016-03-19 00:58:32

标签: swift sorting generics set

在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
}

1 个答案:

答案 0 :(得分:1)

您需要约束您的通用占位符以符合Comparable(以及您已经在做的Hashable)。否则,正如错误消息所示,我们无法保证<适用。

class CustomSet<T: Hashable where T:Comparable>: NSObject {

您的xcrun示例有效,因为Int 符合Comparable。