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

Rap*_*ira 8 reduce dictionary swift

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

类型'[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
}
Run Code Online (Sandbox Code Playgroud)

为什么如果initial被声明为var?它与reduce 签名上@noescape有关吗?

func reduce<U>(initial: U, combine: @noescape (U, T) -> U) -> U
Run Code Online (Sandbox Code Playgroud)

Ant*_*nio 9

您可以dictionary通过前面的参数使参数变为可变var:

var final = array.reduce(initial) { (var dictionary, tuple) in
                                     ^^^
Run Code Online (Sandbox Code Playgroud)

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

  • 如在Swift 2.2(Xcode 7.3)中的Downvote,这会产生一个错误,说明''var'参数已被弃用,并将在Swift 3中删除. (9认同)

mxc*_*xcl 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
}
Run Code Online (Sandbox Code Playgroud)

可以表达的是:

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