Changing value in nested dictionary in swift

前端 未结 3 1640
抹茶落季
抹茶落季 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: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>()  // line1
    dic["key"] = ["a": "a"] // line2
    dic["key"]?["a"] = "b"  // line4
    

提交回复
热议问题