Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift: Add multiple <key, value> objects to NSDictionary

I'm trying to add multiple objects to NSDictionary, like

var myDict: NSDictionary = [["fname": "abc", "lname": "def"], ["fname": "ghi", "lname": "jkl"], ...] 

Is it even possible to do this? If not, please suggest a better way. I actually need to convert this NSDictionary to JSON string and send that to the server, so I need multiple objects in NSDictionary.

like image 983
Srujan Simha Avatar asked Nov 20 '14 17:11

Srujan Simha


1 Answers

You can definitely make a dictionary of dictionaries. However, you need a different syntax for that:

var myDictOfDict:NSDictionary = [     "a" : ["fname": "abc", "lname": "def"] ,   "b" : ["fname": "ghi", "lname": "jkl"] ,   ... : ... ] 

What you have looks like an array of dictionaries, though:

var myArrayOfDict: NSArray = [     ["fname": "abc", "lname": "def"] ,   ["fname": "ghi", "lname": "jkl"] ,   ... ] 

To get JSON that looks like this

{"Data": [{"User": myDict1}, {"User": myDict1},...]} 

you need to add the above array to a dictionary, like this:

var myDict:NSDictionary = ["Data" : myArrayOfDict] 
like image 185
Sergey Kalinichenko Avatar answered Oct 01 '22 17:10

Sergey Kalinichenko