Swift: Extra argument 'error' in call Swift: Extra argument 'error' in call ios ios

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)}


Things have changed in Swift 2, methods that accepted an error parameter were transformed into methods that throw that error instead of returning it via an inout parameter. By looking at the Apple documentation:

HANDLING ERRORS IN SWIFT: In Swift, this method returns a nonoptional result and is marked with the throws keyword to indicate that it throws an error in cases of failure.

You call this method in a try expression and handle any errors in the catch clauses of a do statement, as described in Error Handling in The Swift Programming Language (Swift 2.1) and Error Handling in Using Swift with Cocoa and Objective-C (Swift 2.1).

The shortest solution would be to use try? which returns nil if an error occurs:

let message = try? NSJSONSerialization.JSONObjectWithData(receivedData, options:.AllowFragments)if let dict = message as? NSDictionary {    // ... process the data}

If you're also interested into the error, you can use a do/catch:

do {    let message = try NSJSONSerialization.JSONObjectWithData(receivedData, options:.AllowFragments)    if let dict = message as? NSDictionary {        // ... process the data    }} catch let error as NSError {    print("An error occurred: \(error)")}


This has been changed in Swift 3.0.

 do{            if let responseObj = try JSONSerialization.jsonObject(with: results, options: .allowFragments) as? NSDictionary{                if JSONSerialization.isValidJSONObject(responseObj){                    //Do your stuff here                }                else{                    //Handle error                }            }            else{                //Do your stuff here            }        }        catch let error as NSError {                print("An error occurred: \(error)") }