Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to persist a Realm List property in Swift 4?

Tags:

ios

swift4

realm

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?

like image 259
dr_barto Avatar asked Dec 07 '22 16:12

dr_barto


1 Answers

Realm Lists 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>()
like image 101
allenh Avatar answered Dec 10 '22 11:12

allenh