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

Srujan Simha picture Srujan Simha · Nov 20, 2014 · Viewed 77.3k times · Source

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.

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Nov 20, 2014

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]