gpt4 book ai didi

json - 如何在 Alamofire 中将 nil 与其他 json 值作为参数传递而不收到警告?

转载 作者:行者123 更新时间:2023-11-30 11:52:56 26 4
gpt4 key购买 nike

我收到警告:

Expression implicitly coerced from 'Any?' to Any

在本例中,replyTo 变量是可选的 Int?。我需要它是一个可选值,因为如果它为空,我希望它在服务器端的 json 参数中为空。我可以replyTo ?? 0 并给它一个初始值,但我确实需要它在 json 中为空值。我怎样才能做到这一点而不收到此警告?

let parameters: [String: Any?] = ["replyTo": replyTo, "fromId": fromUser.id, "toId": toUser.id, "message": message]

let urlString = "\(Config.URL)/api/message"

Alamofire.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { (response: DataResponse<Any>) in

}

最佳答案

根据documentation

The Any type represents values of any type, including optional types. Swift gives you a warning if you use an optional value where a value of type Any is expected. If you really do need to use an optional value as an Any value, you can use the as operator to explicitly cast the optional to Any, as shown below.

let optionalNumber: Int? = 3
things.append(optionalNumber) // Warning
things.append(optionalNumber as Any) // No warning

因此,在您的特定情况下,您应该能够执行此操作来抑制警告。

let parameters: [String: Any] = ["replyTo": replyTo as Any, "fromId": fromUser.id, "toId": toUser.id, "message": message]

关于json - 如何在 Alamofire 中将 nil 与其他 json 值作为参数传递而不收到警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48153099/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com