senty senty - 6 months ago 20
iOS Question

Adding 'Key:Value' in Multidimensional Dictionary is Overwriting

I declared and initialized a

[[String:[String:String]
dictionary. It's empty in the beginning, and I am trying to add multiple values under the parent keys.

var dictionary = [String:[String:String]

// some checks

dictionary[i] = ["name" : name]
dictionary[i] = ["from" : country]
dictionary[i] = ["age" : age]


When I do that, I end up having only age key as a child under
[key: [String:String]
. So it's overwriting when I use this approach.

What is the appropriate way of doing

Answer

Your code is creating a new dictionary on each line and assigning this in the dictionary for key i, so you end up with the last dictionary ["age" : age]

You need to create an inner dictionary, assign the values to this and then assign this to your outer dictionary;

var innerDict = [String:String]()
innerDict["name"] = name
innerDict["from"] = from
innerDict["age"] = age

dictionary[i] = innerDict

I would suggest, however, that you look at creating a Struct and put that in your outer dictionary rather than using a dictionary of dictionaries