我根据这个答案创建了NSDictionary类别和覆盖的哈希方法:覆盖 isEqual 的最佳实践:和哈希
@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
和 Swift 实现。
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
}
}
完美地,这还需要实现Equatable
协议,Dictionary
因此您还可以添加Hashable
协议一致性。