gpt4 book ai didi

swift - 泛型类型 'T' 不符合协议(protocol) 'Encodable'

转载 作者:可可西里 更新时间:2023-11-01 00:54:24 25 4
gpt4 key购买 nike

我正在尝试快速使用泛型来解释 http 响应。所有 Json 响应在顶部都有相同的签名:

{
"request": "foo",
"result": "[{},{}....]
}

所以我正在使用这个:

public struct HttpResponse<DATA: Codable>  {
public let request: Bool?
public let result: DATA?

enum CodingKeys: String, CodingKey {
case request= "request"
case result = "result"

} ..

在我的网络层:

final class Network<T: Decodable> {
func getItems(_ path: String) -> Observable<HttpResponse<[T]>> {
let absolutePath = "\(endPoint)/\(path)"
return RxAlamofire
.data(.get, absolutePath)
.debug()
.observeOn(scheduler)
.map({ data -> [T] in
return try JSONDecoder().decode([T].self, from: data)
})
}

我在 Observable<PlutusResponse<[T]>> 中收到此错误

Generics Type 'T' does not conform to protocol 'Encodable'

如何正确使用它?

最佳答案

不匹配:

应该是HttpResponse<DATA: Decodable>而不是 HttpResponse<DATA: Codable> ,见定义Network<T: Decodable> .

Codable 声明符合 Decodable 和 Encodable 协议(protocol),参见 Codable 的定义:

public typealias Codable = Decodable & Encodable

因此您的 HttpResponse 需要一个同时符合 Decodable 和 Encodable 协议(protocol)的泛型。但在 Network 的定义中,使用了仅符合 Decodable 的泛型。因此,一旦编译器检查 getItems 的方法签名,它提示“T”不符合协议(protocol)“Encodable”。

关于swift - 泛型类型 'T' 不符合协议(protocol) 'Encodable',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53355264/

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