简体   繁体   English

如何将混合参数类型传递给 Alamofire 请求

[英]How to pass mixed argument type to Alamofire request

I am trying to send a request with mixed type parameter in Alamofire like below:我正在尝试在 Alamofire 中发送带有混合类型参数的请求,如下所示:

let params = [
    "page": 1,
    "userdIds": [1,2,3],
    "domain": "github.com"
] as [String : Any]

// Error: Type 'Any' cannot conform to 'Encodable'
return try! try! AF.request(url, parameters: params, encoder: URLEncodedFormParameterEncoder.default)

I am getting an error saying:我收到一条错误消息:

Type 'Any' cannot conform to 'Encodable'类型“Any”不能符合“Encodable”


Solution:解决方案:

There is actually solution which can be achieved by using encoding instead of encoder as below:实际上有一个解决方案可以通过使用encoding而不是encoder来实现,如下所示:

return try! AF.request(url, parameters: params, encoding: URLEncoding.default)

Problem with solution:解决方案的问题:

From Documentations : " There are additional methods that allow you to make requests using Parameters dictionaries and ParameterEncoding types. This API is no longer recommended and will eventually be deprecated and removed from Alamofire. " As documentation mentions it will be removed.来自文档:“还有其他方法允许您使用参数字典和 ParameterEncoding 类型发出请求。不再推荐此 API,最终将弃用并从 Alamofire 中删除。 ”正如文档中提到的那样,它将被删除。

Question:题:

Is there any way to resolve this problem without using soon-to-be deprecated method I have mentioned above?有没有什么方法可以在不使用我上面提到的即将被弃用的方法的情况下解决这个问题?

Use an Encodable type:使用Encodable类型:

struct Parameters: Encodable {
  let page: Int
  let userIDs: [Int]
  let domain: String
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM