How to add values in swift dictionary dynamically

2019-07-19 11:05发布

问题:

I have declared a dictionary in my swift class as below :

var profileDetail = Dictionary<String, String>()

But I'm not able to add values in it. IF I try like following, It only stores the last value.

profileDetail = [profileItem[1]:values.valueForKey("middle_name") as String]
profileDetail = [profileItem[2]:values.valueForKey("last_name") as String]
profileDetail = [profileItem[3]:values.valueForKey("gender") as String]
profileDetail = [profileItem[4]:values.valueForKey("birth_date") as String]
profileDetail = [profileItem[5]:"\(add1),\(add2)"]
profileDetail = [profileItem[6]:values.valueForKey("email") as String]

Or following gives me incorrect key exception:

ProfileDetail.setValue(values.valueForKey("first_name") as String, forKey: profileItem[0])
ProfileDetail.setValue(values.valueForKey("middle_name") as String, forKey: profileItem[1])
ProfileDetail.setValue(values.valueForKey("last_name") as String, forKey: profileItem[2])
ProfileDetail.setValue(values.valueForKey("gender") as String, forKey: profileItem[3])
ProfileDetail.setValue(values.valueForKey("birth_date") as String, forKey: profileItem[4])
ProfileDetail.setValue("\(add1),\(add2)", forKey: profileItem[5])
ProfileDetail.setValue(values.valueForKey("email") as String, forKey: profileItem[5]) 

I refereed apple's doc but didn't find anything useful. What is the correct way of adding values in Dictionary dynamically ?

回答1:

In this line you're instantiating a dictionary:

var profileDetail =  Dictionary<String, String>()

identified by the profileDetail variable, but in all other subsequent lines you keep reassigning that variable to something else. Maybe this better explains the error you're making:

var x: Int = 1
x = 2
x = 3
x = 4

Each line assigns a new value to the same variable, so the previous value is lost.

I think you should replace each of those lines with something like:

profileDetail[profileItem[1]] = values.valueForKey("middle_name") as String

or even better you can initialize in a single statement as follows:

var profileDetail = [
    profileItem[1]: values.valueForKey("middle_name"),
    profileItem[2]: values.valueForKey("last_name"),
    ...
]

You can also change var to let if this dictionary, once instantiated, is not supposed to be modified