2

I recently ran into a very time-consuming issue for a simple task of creating a JSON dictionary with optional objects. I'm using SwiftyJSON.

If I create the following dictionary, I get thrown errors

JSON type doesn't have an initializer that supports Dictionary<String,AnyObject?>

But if I simply change AnyObject to an non-optional type, it works.

var dict: Dictionary <String, AnyObject?> = [

      "title" : title as? AnyObject,
      "date" : date as? AnyObject,
]

var jsonData: JSON = JSON(dict)   // this is where I get the error

I need to actually a JSON data set that potentially has nil values, but it seems like SwiftyJSON doesn't allow it.

Is there any way I can create a JSON dictionary with optional objects using SwiftyJSON?

iRiziya
  • 3,235
  • 1
  • 22
  • 36
trixmasta
  • 233
  • 3
  • 14

1 Answers1

2

Neither any key nor any value of a Swift Dictionary can be nil.

You could declare the variable as optional

  var dict: Dictionary <String, AnyObject>?
vadian
  • 274,689
  • 30
  • 353
  • 361