Hash value of NSDictionary

后端 未结 5 1869
温柔的废话
温柔的废话 2020-12-30 07:54

I ran into an issue, where I got the same hash value for different dictionaries. Maybe I\'m doing something obvious wrong, but I thought, objects with different content (a.k

5条回答
  •  旧时难觅i
    2020-12-30 08:39

    I created NSDictionary category and overridden hash method based on this answer: Best practices for overriding isEqual: and hash

    @implementation NSDictionary (Extensions)
    
    - (NSUInteger) hash {
        NSUInteger prime = 31;
        NSUInteger result = 1;
    
        NSArray *sortedKeys = [self.allKeys sortedArrayUsingSelector: @selector(compare:)];
        for (NSObject *key in sortedKeys) {
            result = prime * result + key.hash;
            id value = self[key];
            if ([value conformsToProtocol: @protocol(NSObject)] == YES) {
                result = prime * result + [value hash];
            }
        }
    
        return result;
    }
    
    @end
    

    And Swift implementation.

    extension Dictionary where Key: Comparable, Value: Hashable {
        public var hashValue: Int {
            let prime = 31
            var result = 1
    
            let sortedKeys = self.keys.sorted()
            for (key) in sortedKeys {
                let value = self[key]!
                result = Int.addWithOverflow(Int.multiplyWithOverflow(prime, result).0, key.hashValue).0
                result = Int.addWithOverflow(Int.multiplyWithOverflow(prime, result).0, value.hashValue).0
            }
    
            return result
        }
    }
    

    Perfectly this also requires to implement Equatable protocol for Dictionary so you can also add Hashable protocol conformance.

提交回复
热议问题