Prabhakar Patil Prabhakar Patil - 4 years ago 105
Swift Question

Setting the value in NSDictionary from JSON response

I have parsed the JSON data, now while setting the JSON to my

there might be certain keys in the JSON that might not be present. I want to check if the key is present in the JSON parsed to me and if not, set blank field as value to the key in the `NSDictionary' object.

jsonData = ["id": ((json["idnumber"]) as? String!)!,
"Name": ((json["name"]) as? String!)!,
"Roll Number": ((json["rollnumber"]) as? String!)!,
"Class": ((json["class"]) as? String!)!,
"Marks": ((json["marks"]) as? String!)!,
"Gender": ((json["gender"]) as? String!)!]

So in the above case, the marks field may or may not be present in the JSON. I want to check this and assign respective value to the corresponding key in

I tried using "??", but it takes lot of compilation time.

Answer Source

You can use if let or guard for conditional optional wrapping for that like this.

var jsonData = [String : String]
if let num = json["idnumber"]) as? String {
    jsonData["id"] = num
else {
    jsonData["id"] = num

and so on for others.

Edit: You can also try like this.

var id = name = rollNum = class = ""
if let num = json["idnumber"]) as? String {
    id = num
if let sname = json["name"]) as? String {
    name = sname

Then at last create Dictionary

var jsonData = ["id": id, "name": name, ...]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download