泛型类型 'T' 不符合协议 'Encodable'

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

我正在尝试在 swift 中使用泛型来解释 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 协议,参见 Codable 的定义:

public typealias Codable = Decodable & Encodable

所以您的 HttpResponse 需要一个同时符合 Decodable 和 Encodable 协议的泛型。但在 Network 的定义中,使用了仅符合 Decodable 的泛型。因此,一旦编译器检查 getItems 的方法签名,它就会抱怨 'T' 不符合协议 'Encodable'。