I'm currently developing my first iOS app using Swift 2.0 and Xcode Beta 2. It reads an external JSON and generates a list in a table view with the data. However, I'm getting a strange little error that I can't seem to fix:
Extra argument 'error' in call
Here is a snippet of my code:
let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
print("Task completed")
if(error != nil){
print(error!.localizedDescription)
}
var err: NSError?
if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary{
if(err != nil){
print("JSON Error \(err!.localizedDescription)")
}
if let results: NSArray = jsonResult["results"] as? NSArray{
dispatch_async(dispatch_get_main_queue(), {
self.tableData = results
self.appsTableView!.reloadData()
})
}
}
})
The error is thrown at this line:
if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary{
Can someone please tell me what I'm doing wrong here?
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:
With Swift 3, the name of
NSJSONSerialization
and its methods have changed, according to the Swift API Design Guidelines.Here's the same example:
This has been changed in Swift 3.0.
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 aninout
parameter. By looking at the Apple documentation:The shortest solution would be to use
try?
which returnsnil
if an error occurs:If you're also interested into the error, you can use a
do/catch
: