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"]
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With