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
}
}
Binary operators declared as member functions take one argument; if declared as global functions, they take two arguments. If an operator can be used as either a unary or a binary operator ( &, *, +, and - ), you can overload each use separately. Overloaded operators cannot have default arguments.
As with non-member operator overload functions, you don't have to have both arguments be the same type. However, by definition, the left-hand operand for a member operator function must be an object of the class that the function is a member of.
Again, calling operator functions explicitly is legal, but rare, and usually pointless. As with non-member operator overload functions, you don't have to have both arguments be the same type. However, by definition, the left-hand operand for a member operator function must be an object of the class that the function is a member of.
The first argument for member-function overloaded operators is always of the class type of the object for which the operator is invoked (the class in which the operator is declared, or a class derived from that class). No conversions are supplied for the first argument. Note that the meaning of any of the operators can be changed completely.
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
}
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With