Using Swift 4 and Realm 3.0.1, I'd like to store a list of Realm objects in a property of a parent Realm object. I ran into the following problem:
In Swift 4, properties that should be persisted into Realm have to be @objc dynamic
, e.g. @objc dynamic var id: String = ""
. However, Realm's Array replacement type, List
, can not be stored that way: @objc dynamic var children: List<Child>? = nil
causes this compiler error:
Property cannot be marked @objc because its type cannot be represented in Objective-C
For more context, here's a full example:
final class Child: Object {
@objc dynamic var name: String = ""
}
final class Parent: Object {
// this fails to compile
@objc dynamic var children1: List<Child>?
// this compiles but the children will not be persisted
var children2: List<Child>?
}
So is there another way to store object lists in Realm and Swift 4?
Realm List
s can never be nil
, and they don’t need the @objc dynamic
. They should only be let
, although I can't find that specifically called out in the documentation, there is a comment from a realm contributor that calls it out specifically
There is a cheat sheet for properties in the documentation.
let dogs = List<Dog>()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With