5

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
     }
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
adarshaU
  • 950
  • 1
  • 13
  • 31
  • I think this answers your question: [Member operator '%' must have at least one argument of type 'ViewController’](http://stackoverflow.com/questions/40932230/member-operator-must-have-at-least-one-argument-of-type-viewcontroller) – leanne Mar 18 '17 at 04:34

2 Answers2

6

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 simply:

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

class Equality: Rectangle {
    internal var width: Double = 0
    internal var height: Double = 0
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
4

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
    }
}
Zimes
  • 561
  • 3
  • 13
  • Swift 4.1 does not synthesize conformances for class types. So the second part of your answer will not work with the class `EqualityClass` of the OP. – Luca Angeletti Apr 06 '18 at 10:05
  • 1
    @LucaAngeletti thanks for the correction. I've edited the answer and removed the misleading part – Zimes Apr 06 '18 at 14:22