Changing value in nested dictionary in swift

swift

Solution

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...

Problem

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"] ```

Original source