Sebastian Dwornik
Sebastian Dwornik

Reputation: 2576

How to overcome the error of "Generic parameter 'T' is not used in function signature"?

I'm trying to convert the following to be generic.

extension RLMOrganization: DataProvider {

    func getLastSyncToken() -> String {
        let lastUpdated: RLMOrganization? = self.findAll(sortedBy: "syncToken").last

        if let syncToken = lastUpdated?.syncToken {
            return syncToken
        } else {
            return "00000000000000000000000000000000"
        }
    }


}

And have tried this:

protocol DataProvider: DatabaseLayer {
    associatedtype T: Object

    func findAll<T: Object>(sortedBy key: String) -> [T]
}

extension DataProvider {

func findAll<T: Object>(sortedBy key: String) -> [T] {
    let database = self.getDatabase()

    if let allObjects = database?.objects(T.self) {
        let results = allObjects.sorted(byKeyPath: key, ascending: true)
        return Array(results)
    }

    return []
}


    func getLastSyncToken<T: Object>() -> String {
        let lastUpdated = self.findAll(sortedBy: "syncToken").last as? T

        if let value = lastUpdated?.value(forKey: "syncToken") {  // get value from object by string name
            let syncToken = value as! String
            return syncToken
        } else {
            return "00000000000000000000000000000000"
        }
    }

...

But can't seem to overcome the error of:

Generic parameter 'T' is not used in function signature

enter image description here

I would think the compiler has everything it needs to determine type usage.

Upvotes: 2

Views: 1969

Answers (1)

Joakim Danielson
Joakim Danielson

Reputation: 51892

Below works for me, I don't know how findAll is defined but the problem is the reference to self as I see it so you need to define T there using associatedtype.

protocol DataProvider: DatabaseLayer {
    associatedtype T: Object

    func findAll(sortedBy: String) -> T?
}

Upvotes: 2

Related Questions