0
ジェネリック型のセットを迅速にソートする正しい方法は何ですか?迅速なジェネリックセットのソート
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)、これはアマツバメ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
}
これを行いました。 'class CustomSet' –
'という理由が働かないのは、2つのプレースホルダ、' T'という名前のもの、 'Comparable'というものです。複数の制約を行う唯一の方法は 'where'節です。私のオンラインSwiftの書籍の "Additional Constraints"セクションを参照してください:http://www.apeth.com/swiftBook/ch04.html#_additional_constraints –
matt