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]]

你可能感兴趣的:(try、try?、try!)