我在 Swift 中有一个如下所示的结构:
internal struct MapKey {
internal let id: String
internal let values: [String:String]
}
extension MapKey: Equatable {}
func ==(lhs: MapKey, rhs: MapKey) -> Bool {
return lhs.id == rhs.id && lhs.values == rhs.values
}
我现在有需要使用 MapKey 作为 Swift 字典中的键,这需要 MapKey 符合 Hashable 协议(protocol)。
对于像这样的结构,Hashable 的正确实现应该是什么?
extension MapKey: Hashable {
var hashValue: Int {
return ??? // values does not have a hash function/property.
}
}
我一直在做一些研究,但未能确定哈希字典的正确方法是什么,因为我需要能够为 values 属性本身生成哈希值。非常感谢任何帮助。
最佳答案
如果您必须使用整个结构作为字典键,我认为您需要检查您的数据模型。无论如何,这是一种方法:
internal struct MapKey: Hashable {
internal let id: String
internal let values: [String:String]
var hashValue: Int {
get {
var hashString = self.id + ";"
for key in values.keys.sort() {
hashString += key + ";" + values[key]!
}
return hashString.hashValue
}
}
}
func ==(lhs: MapKey, rhs: MapKey) -> Bool {
return lhs.id == rhs.id && lhs.values == rhs.values
}
这假设您在 id
或 values
的键和值中没有分号 (;
)。 Hasable
意味着 Equatable
所以你不需要再次声明它符合 Equatable
。
关于Swift:具有字典属性的可哈希结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38000867/