== not be called, why?

I have a class A: NSObject, NSCoding {

and inside I define

static func == (lhs: A, rhs: A) -> Bool.

}


a: A

b: A

when I do a == b, func == was not called, why?

Answered by OOPer in 319630022

If using isEqual, I need lots of lines code as below?

No. As I wrote

When Swift imports `NSObject`, it adds a definition of `==` for NSObject which internally calls isEqual(_:) method.


You have no need to call `isEqual` explicitly, and all Optional things are handled in the Standard Library as QuinceyMorris wrote, just if you do the right thing.


You can easily test the code below in the Playground, or making a Command Line Tool project.

import Foundation

class A: NSObject {
    var n: Int = 0
   
    override func isEqual(_ object: Any?) -> Bool {
        print(#function, "called")
        if let other = object as? A {
            return self.n == other.n
        } else {
            return false
        }
    }
   
}

let a = A()
let b = A()

print(a == b)
print(a != b)

let optA: A? = A()
let optB: A? = A()

print(optA == optB)
print(optA != optB)


print(a == optB)
print(optA == b)


No need to define `==`, `!=`, no need to worry about Optionals.

if I add static func ==(lhs: A, rhs: A) -> Bool too,

only A == A will call above function, A != A, A? == A, A == A?, A? == A? won't.

That may happen in some cases. In fact, it is often far from intuitive how overloading for static methods (including operators like `==`) are resolved.


If A is a struct or an enum, you will find that `!=` or `==` for Optionals calls `==` operator you defined.

Generally, you may need to be very careful (or better avoid) defining `==` for subclasses like your `A`.

== not be called, why?
 
 
Q