Changing value in nested dictionary in swift

前端 未结 3 1664
抹茶落季
抹茶落季 2021-01-05 09:00

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

3条回答
  •  佛祖请我去吃肉
    2021-01-05 09:34

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

    When you call this line...

    var dic2 = dic["key"] as Dictionary
    

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

提交回复
热议问题