Alamofire 5 字典中的任何内容

Tol*_*lar 5 ios swift alamofire

我正在尝试使用 Alamofire 5 发出发布请求。我必须使用Dictionary<String, Any>参数。因为我正在为 Alamofire 编写一个包装器。但似乎我无法使用字典中的任何对象,因为 Alamofire 给了我一个编译器错误:

Value of protocol type 'Any' cannot conform to 'Encodable'; only struct/enum/class types can conform to protocols
Run Code Online (Sandbox Code Playgroud)

我尝试过的:

    let encodedParameters = Dictionary<String, Any>

    AF.request(url, method: .get, parameters: encodedParameters, headers: headers)
Run Code Online (Sandbox Code Playgroud)

在我的字典中,某些值将是字符串,其他值将是整数。所以我不能使用常量类型。我该如何解决这个问题?

Swe*_*per 4

要使用 new request,您可以为请求参数创建自己的结构:

// 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
}
Run Code Online (Sandbox Code Playgroud)

你可以传递 aFooRequestParameters(paramName1: 1, paramName1: "hello")而不是你的字典。这与传递字典相同:

[
    "paramName1": 1,
    "paramName2": "hello"
]
Run Code Online (Sandbox Code Playgroud)

此 API 更改背后的理由可能是为了提高安全性。使用[String: Any],您可以很容易地String为应该为 的参数赋予一个值Int,或者错误地键入参数名称,或者在没有意识到的情况下遗漏了一些参数......等等。