12

我正在使用 Xcode 6.4

我有一个 UIViews 数组,我想用 keys 转换为 Dictionary "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]我得到了同样的错误。

有什么清理这个的建议吗?

4

1 回答 1

25

试试这样:

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

Xcode 8 • 斯威夫特 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 • 斯威夫特 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 • 斯威夫特 4.0 - 4.2

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

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

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

extension Collection {
    var indexedDictionary: [String: Element] {
        return Dictionary(uniqueKeysWithValues: enumerated().map{(String($0),$1)})
    }
}
于 2015-07-16T07:02:17.767 回答