Swift 4 Codable&泛型
我正在使用PINCache向我的应用程序添加缓存,并且我处于委托编码/解码方法由缓存系统调用的情况。 这些方法是通用的,但通用值不明确符合Codable
。因为他们是委托人,所以我无法更改签名以使通用类型符合Codable
。Swift 4 Codable&泛型
func modelForKey<T : SimpleModel>(_ cacheKey: String?, context: Any?, completion: @escaping (T?, NSError?) ->()) {
guard let cacheKey = cacheKey, let data = cache.object(forKey: cacheKey) as? Data, T.self is Codable else {
completion(nil, nil)
return
}
let decoder = JSONDecoder()
do {
let model: T = try decoder.decode(T.self, from: data)
completion(model, nil)
} catch {
completion(nil, nil)
}
}
有了这个代码,我有以下错误:
In argument type
T.Type
,T
does not conform to expected typeDecodable
我怎么能强迫我decoder
接受通用的价值?
协议尝试func modelForKey<T : SimpleModel, Decodable> ...
,要求类型被限制为可解码切换到高速缓存库。
IMO问题不在PINCache中。
T.self is Codable
不告诉编译器更多类型T
,所以decoder.decode(T.self, from: data)
将不会通过类型检查,即使T
是Decodable
。
我认为分叉RocketData将是最简单的解决方案(如果您想继续使用RocketData + Decodable
并且所有模型符合Decodable
)。使SimpleModel
符合Decodable
。
尝试创建
CustomProtocol: Codable, SimpleModel
如果点1没有工作,尝试创建自定义类
CustomClass: SimpleModel, Codable
,并使用modelForKey<T : CustomClass>
谢谢,我编辑它 –
能否请您添加代码调用该函数'modelForKey'以及?谢谢;) –