成员运算符'=='必须至少有一个类型的参数

时间:2017-03-18 04:00:58

标签: swift swift3

我正在尝试在equalityClass中实现Equatable协议,但是显示成员运算符'=='必须至少有一个类型为'eqaualityClass'的参数。可以解释这里出错了吗?

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
     }
}

2 个答案:

答案 0 :(得分:2)

您需要使Rectangle协议成为一个类。试试这样:

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
    }
}

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
}

答案 1 :(得分:1)

更优雅的解决方案:

您可以使用协议扩展来使所有采用Rectangle协议的class / struct / enum实体符合Equatable,如下所示:

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
    }
}