I'm learning swift and read a topic about operator overloading in extensions, which likes:
extension StreetAddress: Equatable {
static func == (lhs: StreetAddress, rhs: StreetAddress) -> Bool {
return
lhs.number == rhs.number &&
lhs.street == rhs.street &&
lhs.unit == rhs.unit
}
}
But how i can know i need to adopt the Equatable?
I tried to remove that protocol and the function works the same. No warnings or errors be reported. Why?
Quoting Apple documentation:
To adopt the Equatable protocol, implement the equal-to operator (==) as a static method of your type
so implementing Equatable
means you must overload the ==
operator, hence this is a build error:
extension StreetAddress: Equatable {
}
Overloading the == operator doesn't require and is not strictly related to Equatable
, eg:
class StreetAddress {
var theAddress:String?
static func == (lhs: StreetAddress, rhs: StreetAddress) -> Bool {
return lhs.theAddress?.lowercased() == rhs.theAddress?.lowercased()
}
}