Search code examples
iosswiftrealm

How to pass realm.objects(SomeObject.self).filter() to a function that needs Results<Object>


This question is in conjunction with RealmSwift Cannot cast Results<SomeOjbect> to Results<Object>

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 framework: https://github.com/danielgindi/ChartsRealm, which pull data from Realm and draw charts. The framework is written in Swift, and can be used in Objc as well, so it combines RLMObject and Object types.

It has a function like:

public convenience init(results: Results<Object>?, xValueField: String?, yValueField: String, label: String?)

which takes Results<Object>?, however I cannot get my filter results as Results<Object> type. e.g.

realm.objects(SomeObject.self).filter("city=0")

it's Results<SomeObject>, and cannot be converted to Results<Object>, described in RealmSwift Cannot cast Results<SomeOjbect> to Results<Object>

How can I solve it?

Because the demo in ChartsRealm framework, it simply read all objects from Realm in + (RLMResults *)allObjectsInRealm:(RLMRealm *)realm;, but in real world, we usually need to filt the results first.

If there's really nothing I can do, I could accept modifying the framework function parameters, filing pull requests for the framework, just to make it work.


Solution

  • Results<Object> does not make any sense as a type, and the methods in ChartsRealm should be generic methods which take a Results<T>.

    Because in this specific case all that ChartsRealm does with the Results<Object> is use ObjectiveCSupport.convert() to get a RLMResults, an unsafeBitCast() to Results<Object> should work fine. You could also just call ObjectiveCSupport.convert() yourself and pass ChartsRealm a RLMResults rather than a Swift Results object.