[英]Swift generics - cannot convert value to type
我对 swift 中的 generics 有疑问。
我正在构建简单的 http 客户端,我想扩展它以添加缓存。 我在这里使用这篇出色的帖子构建了缓存解决方案。
我希望能够在初始化时将缓存实例传递给我的客户端,因此它需要能够保存符合Codable
的不同数据类型。
这是我到目前为止所得到的(缓存实现如文章中所述):
数据:
struct CountryResult: Codable {
let meta: Meta //confroms to Codable
let results: [Country] //conforms to Codable
}
缓存:
final class Cache<Key: Hashable, Value> {
// cache implementation
}
// MARK: - Codable
extension Cache.Entry: Codable where Key: Codable, Value: Codable {}
extension Cache: Codable where Key: Codable, Value: Codable {
convenience init(from decoder: Decoder) throws {
self.init()
let container = try decoder.singleValueContainer()
let entries = try container.decode([Entry].self)
entries.forEach(insert)
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(keyTracker.keys.compactMap(entry))
}
}
http 客户端:
struct HttpService {
let service: BaseUrl
let cache: Cache<URL, Codable>
init(service: String = "https://some.service/api", cache: Cache<URL, Codable> = Cache()) {
self.service = service
self.cache = cache
}
// performs http get
func get<T: Codable>(endpoint: String, completion: @escaping (T?, Error?) -> Void) {
guard let url = buildUrl(endpoint) else {
print("Invalid url")
return
}
if let cachedData = cache[url] as? T {
print("Cache hit for: \(url)")
completion(cachedData, nil)
return
} else {
print("Cache miss for: \(url)")
}
//data not in cache, go to network
//....
}
现在,我希望能够在请求不同数据类型的不同视图控制器中实例化这个 http 客户端。 我还想分别保存每个 VC 缓存,因此在初始化 VC 时,我试图查找缓存是否存储到磁盘并像这样加载它:
let urls = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
let cacheUrl = urls[0].appendingPathComponent("/v1/test.cache")
if let data = try? Data(contentsOf: cacheUrl) {
let cache = try? JSONDecoder().decode(Cache<URL, CountryResult>.self, from: data) ?? Cache<URL, CountryResult>()
let httpClient = HttpService(service: "https://some.service/api", cache: cache) //ERROR
}
但我收到以下错误,我不完全理解: Cannot convert value of type 'Cache<URL, CountryResult>?' to expected argument type 'Cache<URL, Codable>' (aka 'Cache<URL, Decodable & Encodable>')
Cannot convert value of type 'Cache<URL, CountryResult>?' to expected argument type 'Cache<URL, Codable>' (aka 'Cache<URL, Decodable & Encodable>')
如果CountryResult
confroms to Codable
aka Decodable & Encodable
为什么它不能被转换
如果您更改以下代码
let cache: Cache<URL, Codable>
作为
let cache: Cache<URL,T: Codable>
在 HttpService 结构中,希望它会起作用。
根据Swift doc ,在 Generics 中,允许具有符合 class 或协议或协议组成的类型参数,而不仅仅是协议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.