Di Wu
Di Wu

Reputation: 6448

Comparing Sets with Arrays inside

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?

Upvotes: 4

Views: 181

Answers (1)

DeFrenZ
DeFrenZ

Reputation: 2252

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.

Upvotes: 2

Related Questions