Member operator '==' must have at least on

2019-07-07 05:59发布

I am trying to implement Equatable protocol in equalityClass, but showing Member operator '==' must have at least one argument of type 'eqaualityClass' .can any one explain whats going wrong here?

protocol Rectangle: Equatable {

    var width: Double { get }
    var height: Double { get }

}

class eqaualityClass:Rectangle{

    internal var width: Double = 0.0
    internal var height: Double = 0.0

      static func == <T:Rectangle>(lhs: T, rhs: T) -> Bool {
          return lhs.width == rhs.width && rhs.height == lhs.height
     }
}

标签: swift swift3
2条回答
霸刀☆藐视天下
2楼-- · 2019-07-07 06:43

A more elegant solution:

You can use a protocol extension to have all your class/struct/enum entities adopting the Rectangle protocol conform to Equatable, like so:

protocol Rectangle: Equatable {
    var width: Double { get }
    var height: Double { get }
}

extension Rectangle {
    static func == (lhs: Self, rhs: Self) -> Bool {
        return lhs.width == rhs.width && rhs.height == lhs.height
    }
}
查看更多
该账号已被封号
3楼-- · 2019-07-07 06:48

You need to make your Rectangle protocol a class. Try like this:

protocol Rectangle: class, Equatable {
    var width: Double { get }
    var height: Double { get }
}

class Equality: Rectangle {
    internal var width: Double = 0
    internal var height: Double = 0
    static func ==(lhs: Equality, rhs: Equality) -> Bool {
        return lhs.width == rhs.width && rhs.height == lhs.height
    }
}

or

protocol Rectangle: class, Equatable {
    var width: Double { get }
    var height: Double { get }
}

extension Rectangle {
    static func ==(lhs: Self, rhs: Self) -> Bool {
        return lhs.width == rhs.width && rhs.height == lhs.height
    }
}

class Equality: Rectangle {
    internal var width: Double = 0
    internal var height: Double = 0
}
查看更多
登录 后发表回答