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

前端 未结 4 978
不知归路
不知归路 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:21

    After lots of research and some trial and error I finally came up with a working solution. The first step was moving the == operator from inside the class to the global scope. This fixed the errors about static and final.

    For the base class this became:

    func == (lhs: Base, rhs: Base) -> Bool {
        return lhs.x == rhs.x
    }
    
    class Base : Equatable {
        var x : Int
    }
    

    And for the subclass:

    func == (lhs: Subclass, rhs: Subclass) -> Bool {
        return true
    }
    
    class Subclass : Base {
        var y : String
    }
    

    Now the only part left is figuring out how to call the == operator of the base class from the == operator of the subclass. This led me to the final solution:

    func == (lhs: Subclass, rhs: Subclass) -> Bool {
        if lhs.y == rhs.y {
            if lhs as Base == rhs as Base {
                return true
            }
        }
    
        return false
    }
    

    That first if statement results in a call to the == operator in the base class.


    The final solution:

    Base.swift:

    func == (lhs: Base, rhs: Base) -> Bool {
        return lhs.x == rhs.x
    }
    
    class Base : Equatable {
        var x : Int
    }
    

    Subclass.swift:

    func == (lhs: Subclass, rhs: Subclass) -> Bool {
        if lhs.y == rhs.y {
            if lhs as Base == rhs as Base {
                return true
            }
        }
    
        return false
    }
    
    class Subclass : Base {
        var y : String
    }
    

提交回复
热议问题