Search code examples
swiftgenericsrealm

Swift: Problems Related to Nested Generic Helper Functions for Realm


I just started to use Realm's swift framework, and not sure if I missed something, but I think the way to query data through realm's API is quite cumbersome, so I want to write a helper function for it.

But when I played with its generic-type function, I came across some problem.

So here is the helper function:

static func queryFromRealm<T: Object>(object: T, query: String) -> Results<T> {
        let realm = try! Realm()
        return realm.objects(T.self).filter(query)
}

realm.objects(type:) is Realm's function, which takes a generic type argument:

public func objects<T: Object>(_ type: T.Type) -> Results<T> {
        return Results<T>(RLMGetObjects(rlmRealm, (type as Object.Type).className(), nil))
}

But when I call this helper method:

let currentUser = STHelpers.queryFromRealm(object: STUser, query: "uid = 'xxxxx'")

I have this error: Cannot convert value of type 'STUser.Type' to expected argument type 'Object', where STUser inherits from Realm's Object class.

I am not sure which step is wrong, and I would really appreciate it for suggestions and help!! Thanks in advance!


Solution

  • Why not just use the type as the parameter instead?

    static func queryFromRealm<T>(type: T.type, query: String) -> Results<T> {
        let realm = try! Realm()
        return realm.objects(type).filter(query) 
    }
    

    you can then call the function with

    let currentUser = STHelpers.queryFromRealm(Student.self, query: "uid = 'xxxxx'")