错误:通过reduce函数传递不可变值 [英] Error: Immutable value passed on reduce function

查看:114
本文介绍了错误:通过reduce函数传递不可变值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


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

类型'[String:String]的不可变值只有名为'updateValue'的变异成员




  var array = [(key0,value0),(key1,value1)] 
var initial = [String:String]()
var final =
dictionary.updateValue(tuple.0,forKey:tuple.1)
返回字典
}

为什么如果初始已被声明为 var ?这是否与缩小版签名中的 @noescape 有关?

  func reduce< U>(初始化:U,组合:@noescape(U,T)→U) - > U 


解决方案

您可以简单地将字典参数可变,前缀为 var

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

请注意,使用减少每个迭代创建一个新的字典,使算法效率低下。您可能需要考虑使用传统 foreach 循环


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 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

这篇关于错误:通过reduce函数传递不可变值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆