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 ?
In this line you're instantiating a dictionary:
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: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:
or even better you can initialize in a single statement as follows:
You can also change
var
tolet
if this dictionary, once instantiated, is not supposed to be modified