我正在使用Xcode 6.4
我有一个UIViews数组,我想用keys转换成Dictionary "v0", "v1"...。像这样:
"v0", "v1"...
var dict = [String:UIView]() for (index, view) in enumerate(views) { dict["v\(index)"] = view } dict //=> ["v0": <view0>, "v1": <view1> ...]
这行得通,但是我正在尝试以更实用的样式进行操作。我想我不得不创建dict变量使我感到困扰。我很乐意使用enumerate()并reduce()喜欢这样:
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])进行此操作,但遇到了同样的错误。
Cannot assign a value of type 'UIView' to a value of type 'UIView?'
UIView
[String]->[String:String]
有什么清理建议吗?
尝试这样:
reduce(enumerate(a), [String:UIView]()) { (var dict, enumeration) in dict["\(enumeration.index)"] = enumeration.element return dict }
Xcode 8•Swift 2.3
extension Array where Element: AnyObject { var indexedDictionary: [String:Element] { var result: [String:Element] = [:] for (index, element) in enumerate() { result[String(index)] = element } return result } }
Xcode 8•Swift 3.0
extension Array { var indexedDictionary: [String: Element] { var result: [String: Element] = [:] enumerated().forEach({ result[String($0.offset)] = $0.element }) return result } }
Xcode 9-10•Swift 4.0-4.2
使用Swift 4 reduce(into:)方法:
reduce(into:)
extension Collection { var indexedDictionary: [String: Element] { return enumerated().reduce(into: [:]) { $0[String($1.offset)] = $1.element } } }
使用Swift 4 Dictionary(uniqueKeysWithValues:)初始化程序并从枚举集合中传递一个新数组:
Dictionary(uniqueKeysWithValues:)
extension Collection { var indexedDictionary: [String: Element] { return Dictionary(uniqueKeysWithValues: enumerated().map{(String($0),$1)}) } }