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

Ada*_*dam 12 functional-programming swift swift2 swift3

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

有关清理的建议吗?

Leo*_*bus 25

试试这样:

reduce(enumerate(a), [String:UIView]()) { (var dict, enumeration) in
    dict["\(enumeration.index)"] = enumeration.element
    return dict
}
Run Code Online (Sandbox Code Playgroud)

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
    }
}
Run Code Online (Sandbox Code Playgroud)

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
    }
}
Run Code Online (Sandbox Code Playgroud)

Xcode 9 - 10•Swift 4.0 - 4.2

使用Swift 4 reduce(into:)方法:

extension Collection  {
    var indexedDictionary: [String: Element] {
        return enumerated().reduce(into: [:]) { $0[String($1.offset)] = $1.element }
    }
}
Run Code Online (Sandbox Code Playgroud)

使用Swift 4 Dictionary(uniqueKeysWithValues:)初始化程序并从枚举集合中传递新数组:

extension Collection {
    var indexedDictionary: [String: Element] {
        return Dictionary(uniqueKeysWithValues: enumerated().map{(String($0),$1)})
    }
}
Run Code Online (Sandbox Code Playgroud)