lwiu
lwiu

Reputation: 179

Updated dictionary values don't persist in array

I just wrote the following code:

var results:[[String:[Int:String]]] = [Dictionary<String, Dictionary<Int,String>>()]
results.removeAll(keepCapacity: false)
results.append(["Swift":[1:"I love you"]])
print(results)

var dict = results[0]
var key = dict[dict.startIndex].0
var updateValue = [2:"I want to marry you"]
var value = dict.updateValue(updateValue, forKey: key)
print(results)

But I found that it doesn't work as expected. The final print still outputs

[[Swift: [1: I love you]]]. and dict.updateValue did succeed!

enter image description here

Upvotes: 2

Views: 61

Answers (1)

Mick MacCallum
Mick MacCallum

Reputation: 130212

Welcome to the world of copy semantics. When you take the first item out of your array with results[0], you aren't making a reference to it, you're taking a copy of the value instead. This means that the Dictionary that you're updating is not the one inside the array.

After you make your updates, just replace the first value in the array with your modified one.

var value = dict.updateValue(updateValue, forKey: key)
results[0] = dict
print(results) // "[[Swift: [2: I want to marry you]]]"

Upvotes: 1

Related Questions