如果未指定关联类型,则无法将协议下传至指定协议

时间:2019-12-07 14:15:42

标签: ios swift

我有一个查询协议

protocol Query {
    associatedtype TResponse: AnyObject
}

可缓存查询的协议和协议

protocol CacheableQuery: Query {
    func load(fromCache cache: Cache) -> Self.TResponse
}

在用于执行此查询的提供程序中,我应将查询下调为CacheableQuery

let cacheableQuery = query as? CacheableQuery

但是编译器返回错误 Error:(19, 40) protocol 'CacheableQuery' can only be used as a generic constraint because it has Self or associated type requirements

然后我为CacheableQuery的TResponse创建约束

func execute<Q>(_ query: Q) -> Q.TResponse where Q : Query {
    let cacheableQuery = self.getCacheableQuery(query: query) // ERROR: Error:(23, 30) generic parameter 'T' could not be inferred
}

    private func getCacheableQuery<Q, T>(query: Q) -> T? 
            where Q: Query,
            T: CacheableQuery, 
            T.TResponse == Q.TResponse {
    let cacheableQuery = query as? T
    return cacheableQuery
}

,我收到另一个错误 Error:(23, 30) generic parameter 'T' could not be inferred

是否可以在不指定协议特定类型的情况下使用协议?或从其他协议中指定关联的类型

0 个答案:

没有答案