SWIFT:呼叫中额外的争论“错误”目前,我正在使用SWIFT2.0和Xcode Beta 2开发我的第一个iOS应用程序,它读取外部JSON,并在表视图中生成包含数据的列表。然而,我遇到了一个奇怪的小错误,似乎无法修复:Extra argument 'error' in call下面是我的代码片段: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()
})
}
}
})此错误将抛出在以下一行:if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary{谁能告诉我在这里做错了什么吗?
3 回答
梵蒂冈之花
TA贡献1900条经验 获得超5个赞
NSJSONSerialization
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary {
print(jsonResult)
}} catch let error as NSError {
print(error.localizedDescription)}NSJSONSerialization
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] {
print(jsonResult)
}} catch let error as NSError {
print(error.localizedDescription)}
蛊毒传说
TA贡献1895条经验 获得超3个赞
errorinout
处理SWIFT中的错误:在SWIFT中,此方法返回一个非可选的结果,并使用抛出关键字标记,以指示在发生故障时抛出错误。
您可以在try表达式中调用此方法,并处理do语句的CATCH子句中的任何错误,如SWIFT编程语言中的错误处理(SWIFT 2.1),以及在使用SWIFT与Cocoa和Object-C(SWIFT 2.1)时的错误处理。
try?nil
let message = try? NSJSONSerialization.JSONObjectWithData(receivedData, options:.AllowFragments)if let dict = message as? NSDictionary {
// ... process the data}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)")}
ABOUTYOU
TA贡献1812条经验 获得超5个赞
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)") }- 3 回答
- 0 关注
- 764 浏览
添加回答
举报
0/150
提交
取消
