错误:传递reduce函数的不可变值

时间:2015-06-10 15:00:56

标签: swift dictionary reduce

我试图执行以下代码,将元组数组转换为字典但我收到编译错误说:

  

类型的不可变值' [String:String]'只有名为' 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
}

为什么初始被声明为 var ?是否与缩小&#39> 签名上的 @noescape 有关?

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

3 个答案:

答案 0 :(得分:9)

您可以通过在dictionary前面加上var参数,使其变得可变:

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

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

答案 1 :(得分:5)

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: [:]){ $0[$1.0] = $1.1 }

答案 2 :(得分:4)

在Swift 3上:

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