0

I'm trying to create a router (enum) for an API in my iOS app.

I have several encodable structs like this one:

struct APIAccountID: Encodable, Decodable {
    
    let username: String
    let password: String
}

In my router, for each request, I have computed variables containing switches that returns baseURL, path, method, and parameters depending on the request. They all work except the parameters variable.

Here is my parameters variable in my router:

var parameters: Encodable? {
        switch self {
        case .fetchAccessToken(let accountID):
            return accountID // Encodable struct AccountID
        case .sendMessage(let message):
            return message // Encodable struct Message
        default:
            break
        }
        return nil
    }

These parameters are used in this Alamofire URLRequestConvertible protocol method:

func asURLRequest() throws -> URLRequest {
        let url = try baseURL.asURL().appendingPathComponent(path)
        var request = URLRequest(url: url)
        request.method = method
        if method == .get {
            request = try URLEncodedFormParameterEncoder()
                .encode(parameters, into: request)
        } else if method == .post {
            request = try JSONParameterEncoder().encode(parameters, into: request)
            request.setValue("application/json", forHTTPHeaderField: "Accept")
        }
        return request
    }

I'm getting this error in the above method:

Protocol 'Encodable' as a type cannot conform to the protocol itself

I'm following this guide to create an API router. But he uses simple dictionaries as parameters. I want to be able to use my Encodable structs. I was looking for using generics but I don't know how in a computed variable. I have read this answer but it didn't help me.

Paul Bénéteau
  • 775
  • 2
  • 12
  • 36
  • The error means what it says, a protocol cannot conform to itself. If `accountID` is `APIAccountID` then `parameters` is clearly `APIAccountID?` – vadian Sep 11 '21 at 20:11
  • @vadian Yeah but in this example only have one case of switch. In the future I will return multiple structs from parameters. I want it to handle any encodable struct… – Paul Bénéteau Sep 11 '21 at 20:23
  • @vadian I just updated my question to make it more clear. – Paul Bénéteau Sep 11 '21 at 20:25

0 Answers0