Writing a good Hashable implementation in Swift

后端 未结 1 1956
鱼传尺愫
鱼传尺愫 2020-12-30 00:20

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

- (NSUInteger)hash {
   return 31u         


        
相关标签:
1条回答
  • 2020-12-30 00:42

    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

    0 讨论(0)
提交回复
热议问题