Reputation: 16430
I'm trying to encode a Dictionary using a JSONEncoder
. The encoded object will be passed to httpBody
as parameter for an URLRequest
.
I can't find a way to set the parameters to be valid encodable items, here is my current code:
class MyRequest{
var parameters:[String:Encodable] = [:]
.....
func urlRequest()->URLRequest{
var request = URLRequest(url:MyURL)
let encoder = JSONEncoder()
do {
let jsonBody = try JSONEncoder().encode(parameters) // ERROR HERE
request.httpBody = jsonBody
}
.....
}
}
I'm receive this error at the line where I'm trying to encode
Protocol type 'Encodable' cannot conform to 'Encodable' because only concrete types can conform to protocols
Upvotes: 0
Views: 680
Reputation: 285092
The error means exactly what it says. The object to encode must be a concrete type conforming to Encodable
A possible solution is to make the class generic
class MyRequest<T : Encodable> {
var parameters:[String:T] = [:]
.....
func urlRequest()->URLRequest{
var request = URLRequest(url:MyURL)
let encoder = JSONEncoder()
do {
let jsonBody = try JSONEncoder().encode(parameters)
request.httpBody = jsonBody
}
.....
}
}
Upvotes: 1