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.