Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass no options to NSJSONSerialization.JSONObjectWithData in Swift

Tags:

ios

swift

swift2

I want to pass no options when deserializing JSON in Swift (2.0). I originally tried:

NSJSONSerialization.JSONObjectWithData(data, options: nil)

But that doesn't compile, I get the error:

Type NSJSONReadingOptions does not conform to protocol NilLiteralConvertible

The enum NSJSONReadingOptions doesn't have any 'None' option, so what do I do if I don't want of any of these options?

like image 200
markdb314 Avatar asked Jul 29 '15 18:07

markdb314


3 Answers

In swift 2 you should use the empty array [] to indicate no options:

NSJSONSerialization.JSONObjectWithData(data, options: [])
like image 67
luk2302 Avatar answered Oct 16 '22 20:10

luk2302


tldr; Swift 3: Just skip the options param and all will be well.

JSONSerialization.jsonObject(with: data)

Explanation:

in swift 3, the function call is

class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> AnyObject

ReadingOptions is an option set, the header for Option Set protocol has

/// When you need to create an instance of an option set, assign one of the
/// type's static members to your variable or constant. Alternately, to create
/// an option set instance with multiple members, assign an array literal with
/// multiple static members of the option set. To create an empty instance,
/// assign an empty array literal to your variable.
///
///     let singleOption: ShippingOptions = .priority
///     let multipleOptions: ShippingOptions = [.nextDay, .secondDay, .priority]
///     let noOptions: ShippingOptions = []

The option set docs are here

which means you can call

JSONSerialization.jsonObject(with: data, options: [])

however, the options already has the default [] defined in the function definition, so you can skip it entirely and call

JSONSerialization.jsonObject(with: data)
like image 8
Confused Vorlon Avatar answered Oct 16 '22 20:10

Confused Vorlon


You can also use an empty constructor for the NSJSONReadingOptions object.

NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
like image 1
Leo Landau Avatar answered Oct 16 '22 18:10

Leo Landau