Error: Immutable value passed on reduce function

Error: Immutable value passed on reduce function

我正在尝试执行以下将元组数组转换为字典的代码,但我收到编译错误消息:

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
}

为什么 initial 被声明为 var?它与 @noescapereduce 的 签名上有关吗?

func reduce<U>(initial: U, combine: @noescape (U, T) -> U) -> U

您只需在 dictionary 参数前面添加 var:

即可使其可变
var final = array.reduce(initial) { (var dictionary, tuple) in
                                     ^^^

但是请注意,使用 reduce 每次迭代都会创建一个新字典,这使得算法效率非常低。您可能需要考虑使用 传统 foreach 循环

在 Swift 3:

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

Swift 4 有一个新变种:

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

可以表示为:

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