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 retur
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...
Yes, in swift structs are passed by value not reference. In other words, you are getting a copy, with the same values. As I understand it, it actually does some optimization under the hood, whereby it doesn't actually make the copy until you change something. Regardless, what you get is a separate instance of the dictionary.
Same thing goes for arrays.
Roman is correct that when you created dic2
, because dictionaries pass by value, you're creating a new dictionary.
You could either copy the dictionary back in, as outlined Access a dictionary in dictionary or you can modify the dictionary in place:
var dic = [String: [String: String]]() // Dictionary<String, Dictionary<String, String>>() // line1
dic["key"] = ["a": "a"] // line2
dic["key"]?["a"] = "b" // line4