-1

I am trying to Parse a json. Casting to [String,AnyObject?] fails. while [String,AnyObject] succeeds

   if let jsonDictionary = try! NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableContainers) as? Dictionary<String,AnyObject?>  {
         print(jsonDictionary["output"])
   }
   else {
       print("Parsing Error")
   }

The above parsing fails, while the below succeeds

   if let jsonDictionary = try! NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableContainers) as? Dictionary<String,AnyObject>  {
         print(jsonDictionary["output"])
   }
   else {
       print("Parsing Error")
   }

I want to know why this happens.

sparrowceg
  • 81
  • 6

1 Answers1

2

By definition all keys and values in a Swift dictionary must be non-optional.

Swift dictionary is bridged to Foundation NSDictionary and there the documentation says

Neither a key nor a value can be nil

By the way: In Swift setting a value for a given key to nil removes the key

vadian
  • 274,689
  • 30
  • 353
  • 361
  • from your explanation one key is removed what about the other keys?. will this cause whole json parse fail? – sparrowceg Apr 21 '16 at 12:52
  • That means for example if you have a dictionary `["alpha" : 1, "beta" : 2]` and you write `dict["beta"] = nil` it's the same as `[dict removeObjectForKey:@"beta"]` in ObjC. The other keys are not affected. – vadian Apr 21 '16 at 12:59
  • So parsing will succeed anyway.. any clue why json parser fails here..i am using Swift 2.1 – sparrowceg Apr 21 '16 at 13:06
  • 1
    If `Parsing Error` is printed then the JSON object is not a dictionary. If the code crashes because of `try!` catch the error properly. If `nil` is printed then the key `output` does not exist. – vadian Apr 21 '16 at 13:20