Search code examples
iosswiftrealmequatable

Comparing Objects Realm Swift


I'm trying to compare 2 Realm Objects in Swift.

// Object 1 Prints:

currentObject:  Optional(ObjectClass {
    order = 0;
    number = 010;
    temp = 903;
    state = 6;

})

// Object 2 Prints:

 lastObject:  Optional(ObjectClass {
        order = 0;
        number = 010;
        temp = 903;
        state = 6;

    })

Obviously the values are equal. But the Objects are not.

print(lastObject?.number == currentObject?.number) // Prints True
print(lastObject == currentObject) // Prints False

I tried to implement equatable in the object class. But Xcode isn't liking it due to Realm.

Redundant conformance of 'ObjectClass' to protocol 'Equatable'

How can I compare the variables of lastObject to currentObject? I imagine theres a better way than checking each object's variable against each other. But I don't know what it is.

Object Class:

import UIKit
import RealmSwift

class ObjectClass: Object {

    @objc dynamic var order = 0
    @objc dynamic var number = ""
    @objc dynamic var temp = 0
    @objc dynamic var state = 1

}

Solution

  • Realm objects already conform to Equatable and Hashable since they are subclasses of NSObject. The only thing you need to do is override the isEqual method:

    import RealmSwift
    
    class ObjectClass: Object {
    
        @objc dynamic var order = 0
        @objc dynamic var number = ""
        @objc dynamic var temp = 0
        @objc dynamic var state = 1
    
        override func isEqual(_ object: Any?) -> Bool {
            if let object = object as? ObjectClass {
                return self.order == object.order && self.number == object.number 
                       && self.temp == object.temp && self.state == object.state
            } else {
                return false
            }
        }
    }