4

In Objective-C you can easily initialize NSSet objects that contains NSArray objects as elements. And you can easily compare those NSSet objects thanks to the isEqual: method.

Now in Swift, which is much more strongly typed, we can no longer do this. The following declaration will receive a "Type [Int] does not conform to protocol Hashable" error.

var set: Set<[Int]>

I am now trying to compare the equality of two groups of arrays that contain a bunch of Int numbers, I want to take advantage of the "isEqual:" idea with Set and Array in Swift, What should I do?

4
  • Well I thought, just make an Array extension and make it Hashable, but as this requires a var hashValue, it cannot be defined in another module, sadly.
    – vrwim
    Commented May 10, 2015 at 12:02
  • Not true, hashValue can be a computed property as well, which can be added in extensions without issues.
    – DeFrenZ
    Commented May 12, 2015 at 10:35
  • @DavideDeFranceschi Yes, but hashValue needs to be declared public, which cannot be added in extensions.
    – vrwim
    Commented May 13, 2015 at 8:31
  • extension NSArray: Equatable {} public func ==(lhs: NSArray, rhs: NSArray) -> Bool { return lhs.isEqualToArray(rhs as [AnyObject]) } extension NSArray: Hashable { var hashable: Int { return 1 } } let fooSet: Set<NSArray> = [NSArray(array: [1, 2])] fooSet.dynamicType This compiles on my playground (sorry can't format long code in comments?)
    – DeFrenZ
    Commented May 13, 2015 at 9:59

1 Answer 1

2

The issue here is thinking: why can't I do that with the standard library? Set requires Hashable items, which have to be Equatable as well. This means that doing Set<Array<T>> would require Any Array to be checked for equality with others. But if T is not Equatable, how do you compare them? Not being able to (still?) declare conditional extensions leads to this :(

I think your best bet (without messing too much with extensions on the standard library) is either use NSSet/NSArray in Swift too, or define at least one of the two parts (Set and Array) as a wrapper.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.