2014-09-04 23 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]