Search code examples
listrealmswift3

Why is it possible to reassign a List<T> property in Realm?


In Realm, it is required to name a List<T> property as let, like:

class Dog:Object {
    dynamic name = "doggy"
    let mate = List<Dog>()
}

let dog1 = Dog()
dog1.name = "Bark"
let dog2 = Dog()
dog2.name = "Brave"
dog1.mates.append(dog2)

As mates is a let variable. You can't reassign it by

let dog3 = Dog()
dog3.name = "Bright"
dog3.mates.append(dog2)
//dog1.mates = dog3.mates // Cannot assign to property: 'mates' is a 'let' constant

But you can reassign it by

dog1["mates"] = dog3.mates // works
dog1.setValue(dog3.mates, forKey: "mates") //works

My question is why "reassign a let variable" allows?


Solution

  • All model properties in Realm are mutable under the hood. However, generic properties don't generate objective-c getters and setters, and therefore can't be overridden, which is why List and RealmOptional properties in Realm must be defined as let, because if they were var and re-assigned via the native setter, Realm wouldn't know about and Bad Things would happen.

    Since Realm can handle setValue(_:forKey:), that works.