Changing value in nested dictionary in swift

前端 未结 3 1641
抹茶落季
抹茶落季 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<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...

    0 讨论(0)
  • 2021-01-05 09:39

    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.

    0 讨论(0)
  • 2021-01-05 09:40

    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
    
    0 讨论(0)
提交回复
热议问题