码迷,mamicode.com
首页 > 编程语言 > 详细

swift try try? try!

时间:2018-09-30 18:24:08      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:https   some   ash   HERE   catch   ras   called   pre   fun   

try

You have 2 options when you try calling a function that may throw.

You can take responsibility of handling errors by surrounding your call within a do-catch block:

Or just try calling the function, and pass the error along to the next caller in the call chain:

try!

What happens when you try to access an implicitly unwrapped optional with a nil inside it? Yes, true, the app will CRASH! Same goes with try! it basically ignores the error chain, and declares a “do or die” situation. If the called function didn’t throw any errors, everything goes fine. But if it failed and threw an error, your application will simply crash.

try?

A new keyword that was introduced in Xcode 7 beta 6. It returns an optional that unwraps successful values, and catches error by returning nil.

Or we can use new awesome guard keyword:

One final note here, by using try? note that you’re discarding the error that took place, as it’s translated to a nil. Use try? when you’re focusing more on successes and failure, not on why things failed.

 

https://stackoverflow.com/questions/32390611/try-try-try-what-s-the-difference-and-when-to-use-each

swift try try? try!

标签:https   some   ash   HERE   catch   ras   called   pre   fun   

原文地址:https://www.cnblogs.com/feng9exe/p/9732571.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!