Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing value in nested dictionary in swift

Tags:

swift

I am wondering why when setting the value of a nested dictionary, the containing dictionary does not reflect those changes? On line3, is a copy of the dictionary being returned?

var dic = Dictionary<String, AnyObject>()  // line1
dic["key"] = ["a":"a"] // line2
var dic2 = dic["key"] as Dictionary<String, String> // line3
dic2["a"] = "b" // line4
dic // key : ["a":"a"], would expect ["a":"b"]
like image 369
Matthew Chung Avatar asked Feb 20 '15 16:02

Matthew Chung


1 Answers

It's because dictionaries are value types and not reference types in Swift.

When you call this line...

var dic2 = dic["key"] as Dictionary<String, String>

... you are creating an entirely new dictionary, not a reference to the value in dic. Changes in dic2 will not be reflected in dic, because dic2 is now a second entirely separate dictionary. If you want dic to reflect the changes that you made, you need to reassign the value to the appropriate key in dic, like this:

dic["key"] = dic2

Hope that helps...

like image 188
Aaron Rasmussen Avatar answered Sep 19 '22 20:09

Aaron Rasmussen