This question already has an answer here:
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?
try like this:
Xcode 8 • Swift 2.3
Xcode 8 • Swift 3.0
Xcode 9 - 10 • Swift 4.0 - 4.2
Using Swift 4
reduce(into:)
method:Using Swift 4
Dictionary(uniqueKeysWithValues:)
initializer and passing a new array from the enumerated collection: