Andrii Liakh
Andrii Liakh

Reputation: 619

Can't convert Realm list from List<SpecificObject> to List<Object>

I'm working on a library for Realm synchronization using CloudKit (https://github.com/caiyue1993/IceCream).

What I'm trying to do is to access a realm object property that is a List<SpecificObject> via parentObject["propertyName"].

Since I can't directly reference the SpecificObject type, so I'm trying to cast this to List<Object> like this:

parentObject["propertyName"] as? List<Object>

but this produces nil.

Same result for casting to AnyRealmCollection<Object>.

It successfully casts to ListBase, which is a superclass of List<T>, but this is useless.

Any ideas on what I may be doing wrong, or should I submit this as an issue to the RealmCocoa repo?

Upvotes: 1

Views: 304

Answers (1)

David Pasztor
David Pasztor

Reputation: 54805

Since generic types in Swift are invariant, List<Object> and List<ObjectSubclass> are two completely unrelated types. Hence the failing cast in your code.

Without knowing the exact type that's being stored in the List, it's impossible to transform a List<ObjectSubclass> to a List<Object> type due to them being invariant.

Upvotes: 1

Related Questions