gpt4 book ai didi

Swift 4 Codable 和泛型

转载 作者:搜寻专家 更新时间:2023-10-30 22:31:49 24 4
gpt4 key购买 nike

我正在使用 PINCache 向我的应用程序添加缓存,并且我处于缓存系统调用编码/解码委托(delegate)方法的情况。这些方法是通用的,但通用值不明确符合 Codable。因为它们是委托(delegate),所以我无法更改签名以使泛型类型符合 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 type Decodable

如何强制我的解码器接受通用值?

最佳答案

由于 Codable 不能在扩展中实现(现在?)并且因为 SimpleModel 是 PINCache 的内部,所以你不能让它符合 Codable。

如果可能的话,我会建议使用支持 Codable 的协议(protocol)的缓存库,例如 Cache

关于Swift 4 Codable 和泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46711304/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com