In swift, is it possible to use the shorter guard let try?
and get the occuring exception if entering the else block?
guard let smth = try? myThrowingFunc() else { print(error) //can I access the exception here somehow? return }
vs
let smth: AnyObject? do { smth = try myThrowingFunc() } catch let error { print(error) return }
The try/catch syntax was added in Swift 2.0 to make exception handling clearer and safer. It's made up of three parts: do starts a block of code that might fail, catch is where execution gets transferred if any errors occur, and any function calls that might fail need to be called using try .
In Swift, we use the guard statement to transfer program control out of scope when certain conditions are not met. The guard statement is similar to the if statement with one major difference. The if statement runs when a certain condition is met. However, the guard statement runs when a certain condition is not met.
I have found page no 42 in "The Swift Programming Language (Swift 2.2 Prerelease)" where it states explicitly the following:
Another way to handle errors is to use
try?
to convert the result to an optional. If the function throws an error, the specific error is discarded and the result isnil
. Otherwise, the result is an optional containing the value that the function returned.
So, this would rather be a feature request for apple then. As a matter of fact there's already some discussion on this topic here:
http://thread.gmane.org/gmane.comp.lang.swift.evolution/8266
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With