How to handle hash collisions for Dictionaries in Swift

后端 未结 4 1222
隐瞒了意图╮
隐瞒了意图╮ 2020-12-17 14:15

TLDR

My custom structure implements the Hashable Protocol. However, when hash collisions occur while inserting keys in a Dictionary, they are not auto

4条回答
  •  执念已碎
    2020-12-17 14:48

    You can see my comments on this page's answers and this answer. I think all answers are still written in a VERY confusing way.

    tl;dr 0) you don't need to write the implementation isEqual ie == between the hashValues. 1) Only provide/return hashValue. 2) just implement Equatable as you normally would

    0) To conform to hashable you must have a computed value named hashValue and give it an appropriate value. Unlike equatable protocol, the comparison of hashValues is already there. You DON'T need to write:

    func ==(lhs: MyStructure, rhs: MyStructure) -> Bool {
        return lhs.hashValue == rhs.hashValue
        // Snippet A
    }
    

    1) Then it uses the hashValue to check to see if for that hashValue's index (calculated by its modulo against the array's count) the key being looked exists or not. It looks within the array of key/value pairs of that index.

    2) However as a fail safe ie in case there are matching hashes you fall back to the regular == func. (Logically you need it because of a fail safe. But you also you need it because Hashable protocol conforms to Equatable and therefore you must write an implementation for ==. Otherwise you would get a compiler error)

    func == (lhs: MyStructure, rhs: MyStructure) -> Bool {
        return lhs.id == rhs.id
        //Snippet B
    }
    

    Conclusion:

    You must include Snippet B, exclude Snippet A, while also having a hashValue property

提交回复
热议问题