Swift Set of Structure Types

后端 未结 2 1176
悲哀的现实
悲哀的现实 2021-02-07 15:45

Say I have a struct, which could be anything:

struct Cube {
    var x: Int
    var y: Int
    var z: Int
    var width: Int
    // ...
}
         


        
2条回答
  •  终归单人心
    2021-02-07 16:41

    Implementing Hashable protocol consists of two things. First is implementing hashValue and second one is implementing equality operator.

    To have working Hashable protocol important part is equality operator. It has to be implemented in a way that returns true only and only then if two structures contain same values.

    On the other hand your hashValue implementation can return literally anything as long as same structure will always return same value.

    The only thing that hashValue influences is how fast will your code work, because when you add or look up for values, first code that will run is hashValue. If hashValue returns same value for two structures, then equality between them will be determined by calling equality operator that would otherwise be skipped.

    struct Cube: Hashable {
    
        // satisfy Hashable requirement
        var hashValue: Int {
            get {
                // you can return any integer here
                return x &+ y &+ z &+...
                // or even the same one for all structs
                return 0
            }
        }
    }
    
    // satisfy Equatable requirement
    func ==(lhs: Cube, rhs: Cube) -> Bool {
        return lhs.x == rhs.x && lhs.y == rhs.y .....
    }
    

提交回复
热议问题