How to properly implement the Equatable protocol in a class hierarchy?

前端 未结 4 977
不知归路
不知归路 2021-01-01 19:53

I\'m trying to implement the == operator (from Equatable) in a base class and its subclasses in Swift 3. All of the classes will only be used in Sw

4条回答
  •  無奈伤痛
    2021-01-01 20:39

    Following the other answers I came up with this:

    class Base : Equatable {
        var x : Int
        static func == (lhs: Base, rhs: Base) -> Bool {
            return lhs.x == rhs.x
        }
    }
    
    class Subclass : Base {
        var y : String
        static func == (lhs: Subclass, rhs: Subclass) -> Bool {
            return lhs.y == rhs.y && (lhs as Base) == (rhs as Base)
        }
    }
    

提交回复
热议问题