Swift:具有字典属性的可哈希结构

标签 swift hashable 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
}

我现在有需要使用 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
}

这假设您在 idvalues 的键和值中没有分号 (;)。 Hasable 意味着 Equatable 所以你不需要再次声明它符合 Equatable

关于Swift:具有字典属性的可哈希结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38000867/

相关文章:

ios - Fabric 的 Shell 脚本调用错误

ios - 无法让 S3 上传在 Xcode 10.2/Swift 中工作

swift - 如何在 SwiftUI 中为 View 之间的过渡设置动画?

Swift: 'Hashable.hashValue' 作为协议(protocol)要求已被弃用;

testing - 使用具有类型列表参数的 Dart 类,如何使其相等

swift - 在 Swift 中将 JSONEncoder 用于 Equatable 方法

ios - 关于 Swift 中复制的问题

python-3.x - 如何使包含 numpy 数组的元组可散列?

swift - 如何使用 Xcode 10 中可用的 API 使枚举符合 Hashable?

flutter - 将属性传递给 Equatable 的 super 构造函数