ios Swift:调用中的额外参数“错误”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31073497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift: Extra argument 'error' in call
提问by kaanmijo
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:
我目前正在使用 Swift 2.0 和 Xcode Beta 2 开发我的第一个 iOS 应用程序。它读取外部 JSON 并在包含数据的表视图中生成一个列表。但是,我遇到了一个似乎无法修复的奇怪小错误:
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?
有人可以告诉我我在这里做错了什么吗?
回答by Eric Aya
With Swift 2, the signaturefor NSJSONSerialization
has changed, to conform to the new error handling system.
在Swift 2 中,for的签名NSJSONSerialization
已更改,以符合新的错误处理系统。
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 nameof NSJSONSerialization
and its methods have changed, according to the Swift API Design Guidelines.
随着斯威夫特3,该名称的NSJSONSerialization
和它的方法已根据改变,雨燕API设计指南。
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)
}
回答by Cristik
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:
Swift 2 发生了变化,接受error
参数的方法被转换为抛出该错误的方法,而不是通过inout
参数返回它。通过查看Apple 文档:
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).
在 SWIFT 中处理错误:在 Swift 中,此方法返回一个非可选结果并用 throws 关键字标记以指示它在失败的情况下抛出错误。
您可以在 try 表达式中调用此方法并处理 do 语句的 catch 子句中的任何错误,如 The Swift Programming Language (Swift 2.1) 中的错误处理和将 Swift 与 Cocoa 和 Objective-C 一起使用 (Swift 2.1) 中的错误处理中所述)。
The shortest solution would be to use try?
which returns nil
if an error occurs:
最短的解决方案是使用try?
whichnil
在发生错误时返回:
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/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)")
}
回答by CodeSteger
This has been changed in Swift 3.0.
这在 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)") }