4

In Objective-C I wrote code like the following:

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:someDictionary
                                                   options:0
                                                     error:&error];

I am trying to do the same thing in Swift. With some prompting from Xcode’s syntax checking I wrote it like this:

var jsonError: NSError
let jsonData = NSJSONSerialization.dataWithJSONObject(someDictionary, options: NSJSONWritingOptions(), error: &jsonError)

but this gives me an error: “Could not find an overload for init that accepts the supplied arguments.” I think the problem might be with the NSJSONWritingOptions() bit, and I’m guessing I just have the Swift syntax wrong. I tried replacing NSJSONWritingOptions() with NSJSONWritingOptions(0) and got the same error; I tried replacing it with nil (as suggested by this answer) but I got the error “Could not find an overload for __conversion that accepts the supplied arguments.”

How can I indicate that I want the default JSON writing options, whatever those might be?

Community
  • 1
  • 1
bdesham
  • 15,430
  • 13
  • 79
  • 123

3 Answers3

4

The problem is not the NSJSONWritingOptions; the type of error you're passing should be NSError?, not NSError.

Jesse Rusak
  • 56,530
  • 12
  • 101
  • 102
3

For those who are looking for the Swift 4.2 equivalent, the options parameter is now optional:

var jsonData:Data?
do {
    jsonData = try JSONSerialization.data(withJSONObject: someDictionary)
} catch let parsingError {
    print(parsingError)
}

Or if you are 100% sure dataWithJSONObject will succeed:

let jsonData = try! JSONSerialization.data(withJSONObject:someDictionary)
Axel Guilmin
  • 11,454
  • 9
  • 54
  • 64
  • In Swift 3+ *no options* is the default so the recommended way is to **omit** the parameter `JSONSerialization.data(withJSONObject:someDictionary)` – vadian Nov 28 '18 at 09:45
0

Nicer way with swift will be:

let data = try! NSJSONSerialization.dataWithJSONObject(values, options: [])

to pass empty array...

source

Community
  • 1
  • 1
Ben
  • 3,832
  • 1
  • 29
  • 30