Equatable Swift (NS)Objects

Dev

How to implement equality with different kinds of Swift objects was pretty obvious once I read the documentation, but the errors I got at first were not entirely clear. If you want to show equality between two objects in Swift, you have to do something different depending on if they subclass NSObject or not.

In the case of an NSObject subclass, you would override -isEqual::

override func isEqual(to object: Any?) -> Bool {
    guard let myObject = object as? MyClass else {
        return false
    }
    return uniqueID == myObject.uniqueID 
}

If it’s a pure Swift object, however, you would implement the Equatable protocol and override ==:

extension MyClass: Equatable {
    static func ==(lhs: MyClass, rhs: MyClass) -> Bool {
        return lhs.uniqueID == rhs.uniqueID
    }
}

If you try to implement Equatable on an NSObject subclass, you will either get compiler errors about redundant conformance, or your implementation of == will never be called and you will be confused.

The Author

iOS and Mac developer.

1 Comment

Comments are closed.