我正在尝试用Alamofire 5做一个post请求。 我必须使用dictionary
作为参数。 因为我正在为Alamofire编写包装器。 但是我似乎不能在字典中使用任何对象,因为Alamofire给了我一个编译器错误:
Value of protocol type 'Any' cannot conform to 'Encodable'; only struct/enum/class types can conform to protocols
我试过的:
let encodedParameters = Dictionary<String, Any>
AF.request(url, method: .get, parameters: encodedParameters, headers: headers)
在我的字典中,一些值将是字符串,另一些值将是整数。 所以我不能用常量类型。 如何解决此问题?
要使用新的请求
,可以为请求参数创建自己的结构:
// 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
}
并且您可以传递FooRequestParameters(paramname1:1,paramname1:"hello“)
而不是您的字典。 这将与传递字典相同:
[
"paramName1": 1,
"paramName2": "hello"
]
这种API变化背后的理由很可能有更多的安全性。 使用[string:Any]
,您可以很容易地给一个应该是int
的参数提供一个string
值,或者错误地键入一个参数的名称,或者漏掉一些参数而不知道。。。 等等。
这是因为您使用的是较新的方法,该方法要求参数
参数必须是可编码
。使用较旧的Alamofire方法就可以了:
AF.request(url, method: .get, parameters: encodedParameters, encoding: JSONEncoding.default, headers: headers)
更新:如果你想使用最新的Alamofire5语法,创建一个结构,并确认它是可编码的。 然后创建一个具有值的相同结构的对象并传递它。