Implementing a hash combiner in Swift

后端 未结 2 1565
一整个雨季
一整个雨季 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)
        }
    
    }
    

提交回复
热议问题