根据 Apple 对字典值的定义,由于键可能存在也可能不存在,因此从字典返回的任何值都是可选的
You can also use subscript syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists, a dictionary's subscript returns an optional value of the dictionary's value type. If the dictionary contains a value for the requested key, the subscript returns an optional value containing the existing value for that key.
我正在尝试使用参数字典中的 auth_token 进行网络调用。
let params = ["auth_token" : authToken()]
print(params["auth_token"]) // shows Optional(dwadhuiwahd)
字典中的值不是可选的。我通过 authToken() 函数中的条件绑定(bind)并打印出来来检查这一点。但是,当打印出保存 auth_token 的字典键时,它显示为:
Optional(dawudhawhd)
这导致我的网络请求失败。
Alamofire.request(.GET, urlString, parameters: params, encoding: .JSON).responseJSON {
(response) in
//this fails
}
除非我对网址进行硬编码。
let urlString = "https://staging.travelwithterra.com/api/v1/users/" + agentID + "/agent_info?auth_token=" + authToken()
Alamofire.request(.GET, urlString, encoding: .JSON).responseJSON {
(response) in //this doesnt fail }
我的问题是,为什么 Alamofire 没有考虑到这一点?或者我做错了什么,它杀了我!
********解决方案************
不要使用.JSON 编码! .URL 编码!!!
最佳答案
您只需添加一个感叹号即可。如下所示。
print(params["auth_token"]!) // doesn't show Optional(dwadhuiwahd) :P
关于ios - Alamofire 使用带有字典参数的可选值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38880197/