2
votes

I am trying to use generics in swift to intrepret http response. All The Json responses have the same signature at the top :

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

So I am using this :

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

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

     }   ..

In My Network layer:

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)
        })
}

I get this error in Observable<PlutusResponse<[T]>>

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

How to correctly use this?

1

1 Answers

3
votes

There is a mismatch:

It should be HttpResponse<DATA: Decodable> instead of HttpResponse<DATA: Codable>, see definition Network<T: Decodable>.

Codable declares conformance to both Decodable and Encodable protocols, see the definition of Codable:

public typealias Codable = Decodable & Encodable

So your HttpResponse expects a generic that conforms to both Decodable and Encodable protocol. But in the definition of Network a generic that conforms only to Decodable is used. Therefore as soon as the compiler checks the method signature of getItems, it complains that 'T' does not conform to protocol 'Encodable'.