Search code examples
swiftrealmequatable

RealmObject Equatable redundant message


We have a simple class Person which inherent from realms Object. Now we want that subclass to conform to the Equatable protocol. The very simple code looks like this.

class Person: Object, Equatable {

    dynamic var localID     = "0"
    dynamic var name:String?
}

func ==(lhs: Person, rhs: Person) -> Bool {

    return lhs.localID == rhs.localID
}

We started with realm version 0.98.8 and everything worked as aspected. When we updated to version 0.102.0 (and the other versions between) the complier error message occurs

Error: Redundant conformance of ‚Person‘ to protocol ‚Equatable‘

Not strange enough, if downgrade back to version 0.98.8 the error still remains. Another strange behavior, on one of our developers machine, the same code compiles just fine.

After some research we have no idea what is going on and how to fix or workaround this.


Solution

  • Latest version of RealmSwift implements Equatable by default, you can look at Object.swift from RealmSwift code.

    To override default Equatable behaviour, you can override this function:

    public override func isEqual(object: AnyObject?) -> Bool
    

    After that, existing Swift code with == will return result based on custom condition defined inside isEqual. No need to create func == manually.

    It's still using isEqual due to RLMObjectBase subclassed from NSObject, not pure Swift object.