Change value in nested dictionary in fast

I wonder why, when setting the value of a nested dictionary, the containing dictionary does not reflect these changes? On line 3, is there a copy of the returned word?

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"]
+4
source share
3 answers

This is because dictionaries are value types, not reference types in Swift.

When you call this line ...

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

... , dic. dic2 dic, dic2 . , dic , dic, :

dic["key"] = dic2

, ...

+8

, dic2, , .

, , :

var dic = [String: [String: String]]() // Dictionary<String, Dictionary<String, String>>()  // line1
dic["key"] = ["a": "a"] // line2
dic["key"]?["a"] = "b"  // line4
+4

Yes, in fast structures the value is not reference. In other words, you get a copy with the same values. As far as I understand, this actually does some optimization under the hood, as a result of which it actually does not make a copy until you change anything. No matter what you get, this is a separate copy of the dictionary.

The same goes for arrays.

+1
source

All Articles