ios 不处理从这里抛出的错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40470145/
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
Errors thrown from here are not handled
提问by TibiaZ
I've got this problem trying to parse a JSON on my iOS app:
我在尝试在我的 iOS 应用程序上解析 JSON 时遇到了这个问题:
Relevant code:
相关代码:
let jsonData:NSDictionary = try JSONSerialization.jsonObject(with: urlData! as Data, options: JSONSerialization.ReadingOptions.mutableContainers ) as! NSDictionary
/* XCode error ^^^ Errors thrown from here are not handled */
Could anybody help me ?
有人可以帮我吗?
回答by shallowThought
A possibly thrown error in let jsonData = try JSONSerialization ...
is not handled.
let jsonData = try JSONSerialization ...
不处理可能抛出的错误。
You can ignore a possible error, and crash as penalty if an error occurs:
您可以忽略可能的错误,如果发生错误,则崩溃作为惩罚:
let jsonData = try! JSONSerialization ...
or return an Optional
, so jsonData
is nil
in error case:
或返回一个Optional
,所以jsonData
是nil
在错误情况下:
let jsonData = try? JSONSerialization ...
or you can catch and handle the thrown error:
或者您可以捕获并处理抛出的错误:
do {
let jsonData = try JSONSerialization ...
//all fine with jsonData here
} catch {
//handle error
print(error)
}
You might want to study The Swift Language
你可能想学习The Swift Language