相关疑难解决方法(0)

使用索引将Swift数组转换为Dictionary

我正在使用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],我得到了相同的错误.

有关清理的建议吗?

functional-programming swift swift2 swift3

12
推荐指数
1
解决办法
1万
查看次数

标签 统计

functional-programming ×1

swift ×1

swift2 ×1

swift3 ×1