I'm trying to do the following code that transforms an array of tuples into a dictionary but I'm receiving a compile error saying:
Immutable value of type '[String : String]' only has mutating members named 'updateValue'
var array = [("key0", "value0"), ("key1", "value1")]
var initial = [String: String]()
var final = array.reduce(initial) { (dictionary, tuple) in
dictionary.updateValue(tuple.0, forKey: tuple.1)
return dictionary
}
Why is that if initial was declared as var? Does it have to do with @noescape on reduce's signature?
func reduce<U>(initial: U, combine: @noescape (U, T) -> U) -> U
You can simply make the
dictionary
parameter mutable by preceding it withvar
:Note however that using
reduce
a new dictionary is created at each iteration, making the algorithm very inefficient. You might want to consider using a traditionalforeach
loop