I created an NSDictionary category and an overridden hash method based on this answer: Recommendations for overriding isEqual: and a 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 the 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 } }
It also requires the implementation of the Equatable protocol for the Dictionary so that you can also add Hashable protocol Hashable .
Igor Kulagin
source share