Implementing a hash combiner in Swift

后端 未结 2 1542
一整个雨季
一整个雨季 2021-01-13 11:26

I\'m extending a struct conform to Hashable. I\'ll use the DJB2 hash combiner to accomplish this.

To make it easy to write hash function f

相关标签:
2条回答
  • 2021-01-13 11:31

    Use the method hash(into:) from the Apple Developer Documentation:

    https://developer.apple.com/documentation/swift/hashable

    struct GridPoint {
        var x: Int
        var y: Int
    }
    
    extension GridPoint: Hashable {
    
        static func == (lhs: GridPoint, rhs: GridPoint) -> Bool {
            return lhs.x == rhs.x && lhs.y == rhs.y
        }
    
        func hash(into hasher: inout Hasher) {
            hasher.combine(x)
            hasher.combine(y)
        }
    
    }
    
    0 讨论(0)
  • 2021-01-13 11:51

    You cannot define a parameter of type P if P is a protocol which has Self or associated type requirements. In this case it is the Equatable protocol from which Hashable inherits, which has a Self requirement:

    public static func ==(lhs: Self, rhs: Self) -> Bool
    

    What you can do is to define a generic method instead:

    extension Hashable {
        func combineHash<T: Hashable>(with hashableOther: T) -> Int {
            let ownHash = self.hashValue
            let otherHash = hashableOther.hashValue
            return (ownHash << 5) &+ ownHash &+ otherHash
        }
    }
    
    0 讨论(0)
提交回复
热议问题