我想在字典中的所有键上映射一个函数.我希望像下面这样的东西可以工作,但过滤器不能直接应用于字典.实现这一目标的最简洁方法是什么?
在这个例子中,我试图将每个值递增1.但这对于示例来说是偶然的 - 主要目的是弄清楚如何将map()应用于字典.
var d = ["foo" : 1, "bar" : 2]
d.map() {
$0.1 += 1
}
Run Code Online (Sandbox Code Playgroud) 我正在使用Xcode 6.4
我有一个UIViews数组,我想转换为带键的字典"v0", "v1"....像这样:
var dict = [String:UIView]()
for (index, view) in enumerate(views) {
dict["v\(index)"] = view
}
dict //=> ["v0": <view0>, "v1": <view1> ...]
Run Code Online (Sandbox Code Playgroud)
这有效,但我试图以更实用的方式做到这一点.我想我必须创建dict变量让我感到困扰.我很乐意使用enumerate()并reduce()喜欢这样:
reduce(enumerate(views), [String:UIView]()) { dict, enumeration in
dict["v\(enumeration.index)"] = enumeration.element // <- error here
return dict
}
Run Code Online (Sandbox Code Playgroud)
这感觉更好,但我得到错误:Cannot assign a value of type 'UIView' to a value of type 'UIView?'我已经尝试过其他对象UIView(即:) [String] -> [String:String],我得到了相同的错误.
有关清理的建议吗?