本文介绍了Swift字典图-闭包初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有Swift字典:
private var params = [String : AnyObject]()
其中包含查询项,例如:
This contains query items like:
-
"lat" ="40"
-
"lon" ="100"
我想将此字典映射到 NSURLQueryItem
数组.我想使其笨拙":
I would like to map this dictionary to NSURLQueryItem
array. I want to make it "swifty":
params.map{NSURLQueryItem.init}
但是我得到一个错误.即使我将地图更改为 [String:String?]
.我知道我可以做一些像这样优雅的单线工作.谁能告诉我如何?
But I get an error. Even if I change the map to be [String:String?]
. I know I can do something like this elegant one-liner. Can anybody tell how?
推荐答案
您为字典指定的值是否必须是可选的?在字典中,当您将其键指定为nil时,该条目将被删除.
Does your value for the dictionary need to be an optional? In a dictionary, when you assign its key as nil, the entry is deleted.
var params = [String:String?]()
params["lat"] = "40"
params["lon"] = "100"
params["key"] = "hey"
print(params) //result: ["lat": Optional("40"), "lon": Optional("100"), "key": Optional("hey")]
params["key"] = nil
print(params) //result: ["lat": Optional("40"), "lon": Optional("100")]
我建议使用非可选值字典.我已经成功编写了以下代码:
I suggest using a non optional-value dictionary. I have successfully written the code below:
import UIKit
var params = [String:String]()
params["lat"] = "40"
params["lon"] = "100"
let nsurl = params.map() {NSURLQueryItem.init(name: $0, value: $1)}
print(nsurl)
//Result:
//[<NSURLQueryItem 0x7f8252d29730> {name = lat, value = 40}, <NSURLQueryItem 0x7f8252d29700> {name = lon, value = 100}]
我希望这对您有帮助
这篇关于Swift字典图-闭包初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!