I am trying to make a post request with Alamofire 5. I have to use Dictionary<String, Any>
for parameters. Because I am writing a wrapper for Alamofire. But it seems i can't be able to use Any object in a dictionary because Alamofire gives me a compiler error:
Value of protocol type 'Any' cannot conform to 'Encodable'; only struct/enum/class types can conform to protocols
What i've tried:
let encodedParameters = Dictionary<String, Any>
AF.request(url, method: .get, parameters: encodedParameters, headers: headers)
Some values will be string others will be integer in my dictionary. So i can't use constant type. How can i resolve this problem?
To use the new request
, you can create your own structs for your request parameters:
// you might have...
struct FooRequestParameters : Codable {
let paramName1: Int
let paramName2: String
}
// for another type of request, you might have different parameters...
struct BarRequestParameters: Codable {
let somethingElse: Bool
}
And you can pass a FooRequestParameters(paramName1: 1, paramName1: "hello")
instead of your dictionary. This would be the same as passing the dictionary:
[
"paramName1": 1,
"paramName2": "hello"
]
The rationale behind this API change is likely to have more safety. With a [String: Any]
, you could very easily, say, give a String
value to a parameter that is supposed to be Int
, or type a parameter's name wrongly, or missed some parameters without realising... etc etc.