3

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?

Vaisakh KP
  • 467
  • 1
  • 6
  • 25
Antonio Steve
  • 33
  • 1
  • 4
  • 1
    Conforming to `Equatable` requires that you implement `==`, but implementing `==` does not require that you conform to `Equatable`. – Alexander Dec 15 '17 at 03:29

1 Answers1

6

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()
    }
}
mugx
  • 9,869
  • 3
  • 43
  • 55
  • thank you! I also found the answer in reference: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AdvancedOperators.html – Antonio Steve Dec 15 '17 at 02:50
  • Glad you found it useful. Please feel free to up-vote and accept the answer :) – mugx Dec 15 '17 at 02:52
  • Interesting. In Version 11.2 beta 2 (11B44), the code compiles without having to add Equatable. – Gene Z. Ragan Oct 20 '19 at 20:25