MatterGoal
MatterGoal

Reputation: 16430

Encodable URLRequest parameters from Dictionary

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

Answers (1)

vadian
vadian

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

Related Questions