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 關注
- 730 瀏覽
添加回答
舉報
0/150
提交
取消
