Chenglu
Chenglu

Reputation: 884

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!

Upvotes: 0

Views: 481

Answers (2)

laznrbfe
laznrbfe

Reputation: 66

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

But,I don't think your code is very good.

My code:

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

and

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

Upvotes: 2

koropok
koropok

Reputation: 1413

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'")

Upvotes: 2

Related Questions