美文网首页
Swift中异常处理 —— try

Swift中异常处理 —— try

作者: 薄凉_简书 | 来源:发表于2017-06-26 12:05 被阅读84次
let string = "{\"name\":\"hehe\"}"
let data = string.data(using: .utf8)
        
//方法一:推荐使用 try?,如果解析成功,就有值;解析失败,返回nil
let json = try? JSONSerialization.jsonObject(with: data!, options: [])
        
//方法二:不建议使用 try!,如果解析失败,会崩溃
let json = try! JSONSerialization.jsonObject(with: data!, options: [])
        
//方法三:do catch 手动捕获异常
do {
    let json = try JSONSerialization.jsonObject(with:data!, options: [])
} catch  {
    //输出错误信息
    print(error)
}

相关文章

网友评论

      本文标题:Swift中异常处理 —— try

      本文链接:https://www.haomeiwen.com/subject/hpndcxtx.html