Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

ios - Swift: Extra argument 'error' in call

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...