swift try try? try!
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》学习笔记 (Day 58)—— Swift编码规范之变量或常量声明规范
- 《从零开始学Swift》学习笔记(Day 55)——使用try?和try!区别
- 《从零开始学Swift》学习笔记(Day 11)——数据类型那些事儿?
- hello Kotlin (android 的swift)
- 【Swift 2.0】实现简单弹幕功能
- iOS swift 宏定义
- ios swift 获取屏幕(window)的宽高
- ios swift navigation返回按钮颜色(UINavigationController,navigationBar)
- ios swift bytes:[UInt8]合成一个Int数:左为高位,右为低位
- ios swift UIPickerView的使用 滚动视图
- ios swift 打印Data
- iOS swift 打印当前方法
- 使用Swift开发Cordova的自定义插件
- ios swift学习日记1-Swift 初见
- Swift_3_功能
- Swift 1.1语言第7章 函数和闭包