Swift:具有字典属性的可哈希结构 [英] Swift: Hashable struct with dictionary property
问题描述
我在Swift中有一个结构如下:
I have a struct in Swift that looks like this:
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协议.
I now have the need to use MapKey as the key in a Swift dictionary, which requires MapKey to conform to the Hashable protocol.
对于像这样的结构,Hashable的正确实现是什么?
What would a correct implementation of Hashable be for a struct like this one?
extension MapKey: Hashable {
var hashValue: Int {
return ??? // values does not have a hash function/property.
}
}
我一直在做一些研究,但是未能确定对字典进行哈希处理的正确方法是什么,因为我需要能够为 values 属性本身生成哈希值.非常感谢您的帮助.
I've been doing some research but failed to identify what the proper way to hash a dictionary is, as I need to be able to generate a hash value for values property itself. Any help is much appreciated.
推荐答案
我认为,如果必须使用整个结构作为字典键,则需要检查数据模型.无论如何,这是一种实现方法:
I think you need to review your data model if you have to use a whole struct as a dictionary key. Anyhow, here's one way to do it:
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
.
This assumes that you don't have semicolon (;
) in id
or in the keys and values of values
. Hasable
implies Equatable
so you don't need to declare it conforming to Equatable
again.
这篇关于Swift:具有字典属性的可哈希结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!