How to get object type and data from AnyRealmValue

I am sure this is an obvious answer but how do you get the object type and data from AnyRealmValue?

class SomeObject: Object {
   @Persisted var myObject: AnyRealmValue = .none

how to get SomeObject from the myObject property?

suppose one SomeObject has myObject having a value of

myObject: AnyRealmValue = .int(100)

and another SomeObject has myObject having a value of

myObject: AnyRealmValue = .object(dog)

The best way to get the object type and value is with a switch.

switch myObject {
    case let .object(obj):
    print("Type is Object, value: \(obj)")
    case let .int(i):
    print("Type is Int, value: \(i)")
1 Like


Thanks you for the response - that’s super great info and very helpful.

I think my question was a bit different but I didn’t articulate it in the question very well: I was really asking about different objects stored as .object

Suppose there’s a Person and Dog class and they are stored in an array of AnyRealmValue

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

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

let obj0: AnyRealmValue = .object(dog) //both of these are objects, even through they are different objects
let obj1: AnyRealmValue = .object(person)

let m = MyClass()

Is using case is the proper way to handle this?

for x in m.myList {
    switch x {
    case let .object(obj): //handle objects such as dogs and persons
        switch obj.self {
        case is DogClass:
        case is PersonClass:
            print("not a dog or a person")
    case let .int(i): //handle ints
        print("it was an int; value is \(i)")
    case let .string(s): //handle strings
        print("it as a string; value is \(s)")
        print("it was something else")

case is is a valid way to handle your scenario. You could also do the following to reduce it down even further if you know for sure what your AnyRealmValue will store:

        for item in myClass.myList {
            if let person = item.object(PersonClass.self) {
                print("is a person")
            } else if let dog = item.object(DogClass.self) {
                print("is a dog")
            } else if let i = item.intValue {
                print("is an int")
1 Like