Reputation: 118
What is the correct way to sort a generic typed Set in 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 Version 7.1 beta (7B60), this is a wrapper around swifts Set
type.
items.sort{$0 < $1}
doesn't work
Cannot invoke 'sort' with an argument list of type '((_, _) -> _)'
.
But works in 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
}
Upvotes: 0
Views: 1075
Reputation: 535304
You need to constrain your generic placeholder to conform to Comparable (as well as Hashable, which you are already doing). Otherwise, as the error message says, we cannot guarantee that <
is applicable.
class CustomSet<T: Hashable where T:Comparable>: NSObject {
Your xcrun
example works because Int does conform to Comparable.
Upvotes: 1