Reputation: 2386
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
}
Upvotes: 33
Views: 15587
Reputation: 41
Unfortunately, we can't.
I found Chris Lattner's own response to this question in this discussion.
This is inconsistent with what we currently have, because “if let” and “guard let” match against an optional and succeed iff the optional is present. You were seemingly saying that the presence of “catch” later in the statement would affect this very primitive behavior that we have. I’m not a strong believer in this proposal, because it is adding complexity and sugar, but I haven’t seen strong motivation that it is common. This isn’t to say that it isn’t common and worthwhile, just that I haven’t seen any evidence.
Upvotes: 3
Reputation: 2386
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
Upvotes: 28