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?
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.