相关疑难解决方法(0)

如何在Swift中为Int数组实现Hashable Protocol(自定义字符串结构)

我正在创建一个类似于a的结构String,除了它只处理Unicode UTF-32标量值.因此,它是一个数组UInt32.(有关更多背景,请参阅此问题.)

我想做的事

我希望能够将自定义ScalarString结构用作字典中的键.例如:

var suffixDictionary = [ScalarString: ScalarString]() // Unicode key, rendered glyph value

// populate dictionary
suffixDictionary[keyScalarString] = valueScalarString
// ...

// check if dictionary contains Unicode scalar string key
if let renderedSuffix = suffixDictionary[unicodeScalarString] {
    // do something with value
}
Run Code Online (Sandbox Code Playgroud)

问题

为此,ScalarString需要实现Hashable协议.我以为我可以这样做:

struct ScalarString: Hashable {

    private var scalarArray: [UInt32] = []

    var hashValue : Int {
        get {
            return self.scalarArray.hashValue // error
        } …
Run Code Online (Sandbox Code Playgroud)

arrays string hashtable ios swift

40
推荐指数
2
解决办法
3万
查看次数

如何在Swift中处理字典的哈希冲突

TLDR

我的自定义结构实现了Hashable Protocol.但是,当在a中插入密钥时发生散列冲突时Dictionary,它们不会自动处理.我该如何克服这个问题?

背景

我之前曾问过这个问题 如何在Swift中为Int数组(自定义字符串结构)实现Hashable Protocol.后来我添加了自己的答案,这似乎有效.

但是,最近我hashValue在使用a时发现了碰撞的微妙问题Dictionary.

最基本的例子

我尽可能地将代码简化为以下示例.

定制结构

struct MyStructure: Hashable {

    var id: Int

    init(id: Int) {
        self.id = id
    }

    var hashValue: Int {
        get {
            // contrived to produce a hashValue collision for id=1 and id=2
            if id == 1 {
                return 2 
            }
            return id
        }
    }
}

func ==(lhs: MyStructure, rhs: MyStructure) -> Bool {
    return lhs.hashValue == rhs.hashValue
}
Run Code Online (Sandbox Code Playgroud)

请注意全局函数重载相等运算符(==)以符合 …

dictionary hash-collision hashable swift

14
推荐指数
2
解决办法
2199
查看次数

标签 统计

swift ×2

arrays ×1

dictionary ×1

hash-collision ×1

hashable ×1

hashtable ×1

ios ×1

string ×1