Error: Immutable value passed on reduce function

天涯浪子 提交于 2019-12-01 00:54:53

问题


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

回答1:


You can simply make the dictionary parameter mutable by preceding it with var:

var final = array.reduce(initial) { (var dictionary, tuple) in
                                     ^^^

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 traditional foreach loop




回答2:


Swift 4 has a new variant:

var array = [("key0", "value0"), ("key1", "value1")]
var initial = [String: String]()
var final = array.reduce(into: initial) { dictionary, tuple in
    dictionary[tuple.0] = tuple.1
}

Which could be expressed:

var array = [("key0", "value0"), ("key1", "value1")]
let final: [String: String] = array.reduce(into: [:]){ $0[$1.0] = $1.1 }



回答3:


On Swift 3:

var final = array.reduce(initial) { (dictionary, tuple) -> [String: String] in
    var mutableDictionary = dictionary
    //.... make changes with mutableDictionary
    return mutableDictionary
}


来源:https://stackoverflow.com/questions/30760156/error-immutable-value-passed-on-reduce-function

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