【发布时间】:2015-10-05 11:18:24
【问题描述】:
我使用的是 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> ...]
这行得通,但我正试图以更实用的风格来做到这一点。我想我必须创建dict 变量让我很困扰。我很想像这样使用enumerate() 和reduce():
reduce(enumerate(views), [String:UIView]()) { dict, enumeration in
dict["v\(enumeration.index)"] = enumeration.element // <- error here
return dict
}
这感觉更好,但我得到了错误:Cannot assign a value of type 'UIView' to a value of type 'UIView?' 我已经尝试过使用 UIView 以外的对象(即:[String] -> [String:String]),我得到了同样的错误。
对清理这个有什么建议吗?
【问题讨论】:
标签: swift functional-programming swift2 swift3