如何克服“函数签名中未使用通用参数'T'”的错误?

时间:2018-08-04 15:04:52

标签: swift generics realm

我正在尝试将以下内容转换为通用类型。

extension RLMOrganization: DataProvider {

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

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


}

并尝试过:

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"
        }
    }

...

但似乎无法克服以下错误:

  

函数签名中未使用通用参数'T'

enter image description here

我认为编译器具有确定 type 用法所需的一切。

1 个答案:

答案 0 :(得分:2)

下面为我工作,我不知道findAll的定义,但问题是我看到的对self的引用,因此您需要使用associatedtype定义T。

protocol DataProvider: DatabaseLayer {
    associatedtype T: Object

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