Dictionary如何在Swift中使用Equatable协议?
发布时间:2020-12-14 05:19:27 所属栏目:百科 来源:网络整理
导读:为了解决 this question,我一直在玩一个实现Hashable Protocol的自定义结构体.我试图看到等效运算符重载(==)被调用多少次,这取决于填充字典时是否存在哈希冲突. 更新 @matt写了一个更清晰的自定义结构实例,实现了Hashable协议,并显示了hashValue和== get被调
为了解决
this question,我一直在玩一个实现Hashable Protocol的自定义结构体.我试图看到等效运算符重载(==)被调用多少次,这取决于填充字典时是否存在哈希冲突.
更新 @matt写了一个更清晰的自定义结构实例,实现了Hashable协议,并显示了hashValue和== get被调用的频率.我正在复制his code.看到我的原始例子,看看edit history. 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的例子中,根本没有哈希冲突,而==仍在被调用.在我的其他实验中强制哈希冲突(见这个问题的编辑历史),==似乎被称为随机次数. 这里发生了什么?
那么你的答案是:
https://bugs.swift.org/browse/SR-3330?focusedCommentId=19980&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-19980
|