RealmSwift Cannot cast Results<SomeOjbect> to Results<Object>

a 夏天 提交于 2019-12-24 19:13:51

问题


RealmSwift version: latest master branch

So I have a Realm Object like:

import RealmSwift
class SomeObject: Object
{
    @objc dynamic var datetime = ""
    @objc dynamic var city = 0

    convenience init(city: Int, datetime: String)
    {
        self.init()
        self.city = city
        self.datetime = datetime
    }
}

There is a func call like

static func createlineData(from results: Results<Object>?) -> LineChartData

Now I fetch some results and pass to createLineData:

let realm = try! Realm()
let results = realm.objects(SomeObject.self).filter("city = \(city.rawValue)")
let lineData = createlineData(from: results as? Results<Object>)

compiler warns me that the type cast will always fail:

Cast from Results<"SomeObject"> to unrelated type Results<"Object"> always fails

I am confused since SomeObject is just a subclass. How can I fix it? Thanks in advance.

UPDATE:

What I want to do is that, the param of

static func createlineData(from results: Results<Object>?) -> LineChartData

can never be changed, so I need to make a query to filt based on city which is enum, pass them into createlineData(from results: Results<Object>?), and access other properties like datetime later in createlineData, from Results<Object>


回答1:


In Swift, each generic class represents its own type and even if you have a generic class where the generic type parameter is a subclass of your other generic class having the superclass as its generic parameter, the two generic classes won't be related through inheritance.

This is why you cannot cast Results<SomeObject> to Results<Object> even though SomeObject is a subclass of Object.

Here's a simple example representing the same issue with a generic class:

class A{}
class B:A{}

class GenericClass<T> {
    let val:T

    init(val:T) {
        self.val = val
    }
}

let genericA = GenericClass<A>(val: A())
let genericB = GenericClass<B>(val: B())

let upcasted = genericB as? GenericClass<A> //warning: Cast from 'GenericClass<B>' to unrelated type 'GenericClass<A>' always fails

Moreover, the Results type in Realm is a homogenous collection type, so you cannot store different subclasses of Object in the same Results object, so casting to Results<Object> wouldn't make sense anyways. If you need to store objects from different Realm model classes in the same collection, you will need to sacrifice the self-updating nature of Results and stick with storing your objects in an Array for instance.



来源:https://stackoverflow.com/questions/48125923/realmswift-cannot-cast-resultssomeojbect-to-resultsobject

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!