Search code examples
swiftsetrealm

How to add Realm Objects to Set


I want use set with Realm Object.

Primary keys must not be changed and they must be unique.
So I added another variable for compare.
And I override isEqual(:) function.

class Model: Object {
    @objc dynamic var key = ""
    @objc dynamic var id = ""

    override static func primaryKey() -> String? {
        return "key"
    }

    override func isEqual(_ object: Any?) -> Bool {
        if let object = object as? Model {
            if self.id == object.id {
                return true
            } else {
                return false
            }
        } else {
            return false
        }
    }
}

let model1 = Model()
model1.key = UUID().uuidString
model1.id = "hi"

let model2 = Model()
model2.key = UUID().uuidString
model2.id = "hi"

let model1Array = [model1]
let model2Array = [model2]

let set1 = Set(model1Array)
let set2 = Set(model2Array)

let result = set1.intersection(set2)
print(result) // []

I want use set with Realm object.
But how can I do that??

I need union, intersection, subtracting and more...
I have to compare more than 20,000 models. (20000 * 20000 = 400000000)
It turns out the app is out of memory.
I want to solve this.


Solution

  • Removing self from self.id solves your issue and you'll get the expected results. This seems like a bug, but not sure why it exists. You can also simplify your property equality check to return id == otherModel.id.

    class Model: Object {
        @objc dynamic var key = ""
        @objc dynamic var id = ""
    
        override static func primaryKey() -> String? {
            return "key"
        }
    
        override func isEqual(_ object: Any?) -> Bool {
            if let otherModel = object as? Model {
                return id == otherModel.id
            } else {
                return false
            }
        }
    }