为了解决这个问题,我一直在玩一个实现哈希协议的自定义结构。我试图查看等效运算符重载(==
)被调用多少次,具体取决于填充Dictionary
.
更新
@matt写了一个更简洁的自定义结构示例,它实现了 Hashable 协议并显示了调用频率hashValue
和==
调用频率。我在下面复制他的代码。要查看我的原始示例,请查看编辑历史记录。
struct S : Hashable {
static func ==(lhs:S,rhs:S) -> Bool {
print("called == for", lhs.id, rhs.id)
return lhs.id == rhs.id
}
let id : Int
var hashValue : Int {
print("called hashValue for", self.id)
return self.id
}
init(_ id:Int) {self.id = id}
}
var s = Set<S>()
for i in 1...5 {
print("inserting", i)
s.insert(S(i))
}
这会产生结果:
/*
inserting 1
called hashValue for 1
inserting 2
called hashValue for 2
called == for 1 2
called hashValue for 1
called hashValue for 2
inserting 3
called hashValue for 3
inserting 4
called hashValue for 4
called == for 3 4
called == for 1 4
called hashValue for 2
called hashValue for 3
called hashValue for 1
called hashValue for 4
called == for 3 4
called == for 1 4
inserting 5
called hashValue for 5
*/
由于 Hashable 使用 Equatable 来区分哈希冲突(我无论如何都假设),我希望func ==()
只在存在哈希冲突时被调用。但是,在上面的@matt 示例中根本没有哈希冲突,但==
仍在调用。在我的其他强制哈希冲突的实验中(参见这个问题的编辑历史),==
似乎被称为随机次数。
这里发生了什么?