TLDR: How can one set a linked object property by ObjectId of the linked object independent of whether this object already exists in the Realm Swift SDK? (something like DBRef in JS)
Suppose there are two Realm Objects: Dog and Person, that have a to-one-relationship (i.e. each person can have one linked dog). It is easy to initialise two objects and then link them, just by setting the field dog to the actual dog instance:
let realm = try! Realm()
let dog = realm.create(Dog.self)
let person = realm.create(Person.self)
dog.name = "Bello"
person.name = "Mike"
person.dog = dog
I believe this creates a reference in realm, not actually copies the current dog instance into the person instance.
If I already know the ObjectId that a dog instance, can I initialise a Person instance independent of whether the dog instance is already in the realm or being created later?. When reading the person object later, I should get either nil if the dog with that ObjectId has not been added to the realm, but “automatically” get the dog once the dog has been independently added to the realm. This seems to be possible in JS, using DBRef() (see this SO post). Does something like DBRef exist in the Swift SDK?
class Person: Object {
@Persisted var personName: String = ""
@Persisted var dog: Dog?
}
class Dog: Object {
@Persisted(primaryKey: true) var objectIdName: ObjectId = ObjectId(string: UUID.uuidString())
@Persisted var dogName: String = ""
}
I found nothing in the docs about this issue.




