Why does Realm suggest declaring List <T> properties with "let"?
The real-time documentation on to-many relationships declares a property List<Dog>
using let
:
class Person: Object {
// ... other property declarations
let dogs = List<Dog>()
}
Why is this property List<T>
declared with let
when other types of Realm properties are declared with dynamic var
?
source to share
List<T>
properties must be declared with let
, as Realm cannot intercept assignment to these properties. Assigning to properties List<T>
will not save your changes to the Realm file. By declaring the property with let
, instead of var
, you bring in the Swift compiler to detect code that won't do what you intend.
Instead of assigning properties to properties, List<T>
you must modify the existing property value using methods that are part of the RangeReplaceableCollection
protocol to which it conforms List<T>
.
For example, to add a new dog:
person.dogs.append(lassie)
Or replace existing dogs:
person.dogs.replaceSubrange(0..<person.dogs.count, with: [fido, spot])
Why?
Realm model classes automatically implement getters and setters for your persistent properties that access the underlying database data. To provide these getters and setters, your properties must be declared with a modifier dynamic
. This modifier asks Swift to dynamically dispatch property accesses via getters and setters rather than accessing the member directly at compile time. The modifier dynamic
has a significant limitation: it is only supported for types that can be represented in Objective-C. This is because Swift's dynamic dispatch is built on top of Objective-C runtime. It is this limitation that prevents Realm from intercepting property assignments List<T>
.
source to share