Setup:个
我想使用以下struct
中的Set
:
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)
}
}
我预计在空的Set
中插入两个相等的元素(根据上面定义的函数)会得到一个只有一个元素的Set
:
var pairs: Set<NumberPair> = []
//…
pairs.insert(NumberPair(n1: 1, n2: 2))
pairs.insert(NumberPair(n1: 2, n2: 1))
Problem:个
然而,在第二次插入时,我得到了一个运行时错误
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.
当我在static func ==
中设置断点时,这个断点没有命中.
Question:个
为什么我的自定义相等函数没有被调用,以及如何正确地执行它?