Setup:
I want to use a Set
of the following struct
:
struct NumberPair: Hashable {
let n1: Int
let n2: Int
static func == (lhs: NumberPair, rhs: NumberPair) -> Bool {
lhs.n1 == rhs.n1 && lhs.n2 == rhs.n2 ||
lhs.n2 == rhs.n1 && lhs.n1 == rhs.n2
}
func hash(into hasher: inout Hasher) {
hasher.combine(n1)
hasher.combine(n2)
}
}
I expected that inserting 2 elements that are equal (according to the function defined above) into an empty Set
results in a Set
with a single element:
var pairs: Set<NumberPair> = []
//…
pairs.insert(NumberPair(n1: 1, n2: 2))
pairs.insert(NumberPair(n1: 2, n2: 1))
Problem:
However, at the 2nd insert I get an runtime error
Fatal error: Duplicate elements of type 'NumberPair' were found in a Set.
This usually means either that the type violates Hashable's requirements, or
that members of such a set were mutated after insertion.
When I set a breakpoint in the static func ==
, this breakpoint is not hit.
Question:
Why is my custom equality function not called, and how to do it right?