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?
In swift 2 you should use the empty array []
to indicate no options
:
NSJSONSerialization.JSONObjectWithData(data, options: [])
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)
You can also use an empty constructor for the NSJSONReadingOptions
object.
NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With