Subclasses of `NSObject` should implement `isEqual` instead of `==`SW-W1029
In Swift, the ==
operator performs a reference-based comparison by default.
This means that when comparing two objects using ==
, it checks if the object references are equal, rather than comparing the actual content or properties of the objects.
However, for most NSObject
subclasses, it is more meaningful to compare their properties or content instead of their references. By implementing the isEqual
method, you can define custom equality logic for your objects, allowing you to compare their properties and determine whether they are considered equal.
If you rely solely on the ==
operator for object comparison, it can lead to unexpected behavior and incorrect results. For example, two different instances of the same NSObject
subclass with the same properties may not be considered equal if ==
is used, but they should be considered equal based on the logic defined in the isEqual
method.
Bad Practice
class AClass: NSObject {
static func ==(lhs: AClass, rhs: AClass) -> Bool {
return true
}
}
Recommended
class AClass: NSObject {
override func isEqual(_ object: Any?) -> Bool {
return true
}
}