Swift Realm - get types of all database objects

Viewed 16

I have a list of various objects in my Realm Database all of which are created as default ClassName: Object classes. Is there any way to get types (classes names) of those objects, that can be saved as variables, or create an enum of these types?

1 Answers

The issue is that Realm Results objects are homogenous - they only contain one object type. That translates to meaning you will never have a situation where Results would contain Person and Dog classes at the same time.

That being said we have the option of using the Realm AnyRealmValue

Let me set this up: Suppose you have a PersonClass and a DogClass

let dog = DogClass()
let person = PersonClass()

and a class with a List that can contain AnyRealmValue

class MyClass: Object {
   @Persisted var myList = List<AnyRealmValue>()
}

when then need to cast those objects to AnyRealmValue to make this work

let obj0: AnyRealmValue = .object(dog)
let obj1: AnyRealmValue = .object(person)

and we add those to the List

let m = MyClass()
m.myList.append(obj0)
m.myList.append(obj1)

You mentioned switch but here's a simple if...then clause to handle them differently - depending on the class

if let person = item.object(PersonClass.self) {
   print("is a person")
} else if let dog = item.object(DogClass.self) {
   print("is a dog")
}
Related