6

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?

dr_barto
  • 5,723
  • 3
  • 26
  • 47

1 Answers1

16

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>()
allenh
  • 6,582
  • 2
  • 24
  • 40
  • how do you change the dogs if it's declared with let? – Jan May 17 '18 at 19:20
  • 5
    @Jan `realm.write { dogs.removeAll(); dogs.append(Dog()) }`. This potentially results in detached dogs. You can do `realm.write { person.dogs.forEach { realm.delete($0) }; person.dogs.append(Dog()) }`. Depends on your situation. – allenh May 17 '18 at 19:34
  • Realm List documentation states "Unlike Swift’s native collections, Lists are reference types, and are only immutable if the Realm that manages them is opened as read-only." https://realm.io/docs/swift/latest/api/Classes/List.html – Giles Jul 27 '18 at 07:37
  • @AllenHumphreys Well, just trying to emphasise the mental model that these are not like Swift arrays - mutability is determined by the state of the Realm, not by var/let. – Giles Jul 27 '18 at 15:30
  • 1
    append() data line has to be inside write block or nothing is saved to List – Stephen Shi Feb 28 '20 at 22:23