Writing a good Hashable implementation in Swift

2019-02-04 09:07发布

问题:

In Objective-C (and other languages) a relatively good default implementation of - (NSUInteger)hash might be:

- (NSUInteger)hash {
   return 31u * [self.property1 hash] + [self.property2 hash];
}

Assuming both property1 and property2 return good values for hash.

This doesn't work in Swift's equivalent var hashValue: Int method defined on its Hashable protocol.

The equivalent Swift code is likely to overflow and this a runtime error in Swift.

var hashValue: Int {
    return 31 * property1.hashValue + property2.hashValue // overflow-tastic
}

So my question is, what is the best technique for generating hash values (implementing Hashable) in Swift? Should I just use XOR? Though my understanding is that XOR is not ideal for creating uniform hash distributions. Perhaps something more exotic?

回答1:

As suggested by Fabian Kreiser one can use the overflow operators to make the hashValue method as follows:

var hashValue: Int {
    return (31 &* property1.hashValue) &+ property2.hashValue 
}

The value still overflows, but at least it doesn't crash



标签: hash swift