Convert Swift Array to Dictionary with indexes [duplicate]

♀尐吖头ヾ 提交于 2019-12-17 09:48:18

问题


I'm using Xcode 6.4

I have an array of UIViews and I want to convert to a Dictionary with keys "v0", "v1".... Like so:

var dict = [String:UIView]()
for (index, view) in enumerate(views) {
  dict["v\(index)"] = view
}
dict //=> ["v0": <view0>, "v1": <view1> ...]

This works, but I'm trying to do this in a more functional style. I guess it bothers me that I have to create the dict variable. I would love to use enumerate() and reduce() like so:

reduce(enumerate(views), [String:UIView]()) { dict, enumeration in
  dict["v\(enumeration.index)"] = enumeration.element // <- error here
  return dict
}

This feels nicer, but I'm getting the error: Cannot assign a value of type 'UIView' to a value of type 'UIView?' I have tried this with objects other an UIView (ie: [String] -> [String:String]) and I get the same error.

Any suggestions for cleaning this up?


回答1:


try like this:

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

Using Swift 4 reduce(into:) method:

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

Using Swift 4 Dictionary(uniqueKeysWithValues:) initializer and passing a new array from the enumerated collection:

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


来源:https://stackoverflow.com/questions/31446960/convert-swift-array-to-dictionary-with-indexes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!