2014-09-04 67 views
0

我正在玩迅速功能的东西。我试图为reduce创建一个累加器函数,该函数应该以字典开头,并返回一个新增的字典。如何使用增加的值返回新字典?

基本上这个,但current是不可变的。我必须返回一个新的字典,相当于它会是,如果我做了以下事情:

func newDictionaryWithValueAdded(current:Dictionary<Int, Double>, amount: Int) -> Dictionary<Int, Double> { 
    // current[amount] = amount/100 
    // return amount 
} 

是否有一个功能呢?一些类似阵列concantenation?

+0

同样是这种方法太慢?对于其他不可改变的功能语言来说,这是非常标准的吗? – 2014-09-04 16:40:43

回答

0

您可以声明一个函数参数为变量var。 在以下示例中,current是通过词典的副本(因为 字典是值类型),但所用的功能进行修改:

func newDictionaryWithValueAdded(var current:Dictionary<Int, Double>, amount: Int) -> Dictionary<Int, Double> { 
    current[amount] = Double(amount)/100 
    return current 
} 

let dict1 : [Int : Double] = [:] 
let dict2 = newDictionaryWithValueAdded(dict1, 12) 

println(dict1) // [:] 
println(dict2) // [12: 0.12]