I'm trying to create a generic JSON mapper for my application. I'm using the Codable protocol and I have two functions: one to convert data to decodable and one to convert encodable to data. Here's my implementation:
struct JSONMapper: JSONMapperProtocol {
func map<T: Encodable>(from entity: T) -> Data? {
let encoder = JSONEncoder()
guard let data = try? encoder.encode(entity) else {
return nil
}
return data
}
func map<T: Decodable>(from data: Data) -> T? {
let decoder = JSONDecoder()
guard let entity = try? decoder.decode(T.self, from: data) else {
return nil
}
return entity
}
}
My desirable usage of these functions is this:
if let body = requestData.body {
request.httpBody = self.mapper.map(from: body)
}
requestData is an implementation of this protocol:
protocol RequestData {
var method: HTTPMethod { get }
var host: String { get }
var path: String { get }
var header: [String: String]? { get }
var queryParameters: [String: String]? { get }
var body: Encodable? { get }
}
But the compiler gives me the following error:
Cannot convert value of type 'Encodable' to expected argument type 'Data'
I don't get why this is happening because 'httpBody' is a Data and 'body' is a Encodable. Should't the compiler be able to infer this?
I appreciate any thoughts to solve this issue.
Configuration:
Compiler: Swift 4.2
Xcode: 10.1
requestData.body? - Robert Dreslerbodymust be a concrete type, not the protocolEncodable. - vadian