try、try?、try!

try:

try与do-catch语句一起使用,并对错误进行详细处理。

do {
    let responseJSON = try JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]] 
    /// 解析成功,则处理response数据
    completion(responseJSON)
} catch {
    /// 解析失败,提示用户信息
    print("Hm, something is wrong here. Try connecting to the wifi.")
}

try?

try?用在错误无关紧要的时候,也就是忽略错误时使用

 let responseJSON = try? JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]]   // 返回Optional值
 if let responseJSON = responseJSON {
  // 有值,处理responseJSON值
   print("Yay! We have just unwrapped responseJSON!")
 }

以上代码也可以写作成:

// 除非responseJSON有值,否则为nil的话,return
  guard let responseJSON = try? JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]] else {  return   }

try!

try! 当我们知道此方法不能够失败时,或者如果这行代码是必要条件,如果失败导致我们的整个应用程序崩溃。


  let responseJSON = try! JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]]

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容