senty senty - 1 year ago 139
iOS Question

Adding 'Key:Value' in Multidimensional Dictionary is Overwriting

I declared and initialized a

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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download