In Swift 2.0, Apple introduced a new way to handle errors (do-try-catch).
And few days ago in Beta 6 an even newer keyword was introduced (try?
).
Also, knew that I can use try!
.
What's the difference between the 3 keywords, and when to use each?
相关问题
- “Zero out” sensitive String data in Swift
- SwiftUI: UIImage (QRCode) does not load after call
- Get the NSRange for the visible text after scroll
- UIPanGestureRecognizer is not working in iOS 13
- What does a Firebase observer actually do?
相关文章
- Using if let syntax in switch statement
- Enum with associated value conforming to CaseItera
- Swift - hide pickerView after value selected
- Is there a Github markdown language identifier for
- How can I vertically align my status bar item text
- Adding TapGestureRecognizer to UILabel in Swift
- Attempt to present UIAlertController on View Contr
- Swift - Snapshotting a view that has not been rend
Assume the following throwing function:
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.