unb*_*ant 6 hashable swift equatable
我在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
}
Run Code Online (Sandbox Code Playgroud)
我现在需要使用MapKey作为Swift字典中的键,这需要MapKey符合Hashable协议.
对于像这样的结构,Hashable的正确实现是什么?
extension MapKey: Hashable {
var hashValue: Int {
return ??? // values does not have a hash function/property.
}
}
Run Code Online (Sandbox Code Playgroud)
我一直在做一些研究,但未能确定散列字典的正确方法是什么,因为我需要能够为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
}
Run Code Online (Sandbox Code Playgroud)
这假设的键和值中没有分号 ( ;) 。意味着你不需要再次声明它符合。idvaluesHasableEquatableEquatable
| 归档时间: |
|
| 查看次数: |
2105 次 |
| 最近记录: |