Swift: Extra argument ‘error’ in call

With Swift 2, the signature for NSJSONSerialization has changed, to conform to the new error handling system.

Here’s an example of how to use it:

do {
    if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary {
        print(jsonResult)
    }
} catch let error as NSError {
    print(error.localizedDescription)
}

With Swift 3, the name of NSJSONSerialization and its methods have changed, according to the Swift API Design Guidelines.

Here’s the same example:

do {
    if let jsonResult = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] {
        print(jsonResult)
    }
} catch let error as NSError {
    print(error.localizedDescription)
}

Leave a Comment