Celebrating 200 Daily Coding Tips 🎉 all tutorials will be free to all this week!
Calling a throwing function requires the function call is ‘tried’ inside a do
block that comes with a catch
block. Or does it? There are many situations where you really only want to know if the function call succeeded or not. There are plenty of throwing functions where the error doesn’t actually matter, because the error is just telling us that the function failed.
I have a custom error type here called RandomError
, which only exists when a Boolean value is true. I have a protocol called HasThrowable
which requires a throwingFunction()
, and I have a default implementation of that function that decides whether to throw an error or return a string based on Bool.random()
.
I used a protocol this way just so that I could be sure that the same function is being called in my two views. My two views will be called DoCatchView
and OptionalTryView
, and the difference between them should be pretty obvious.
In DoCatchView
I am using the RandomError.boolWasTrue
as part of a print statement.
When there is an error in OptionalTryView
I have no access to the error, so I don’t print it anywhere. But I have to question whether I really ever wanted it, because it was only ever going to be of type RandomError.boolWasTrue
, and I can assume that was the case if throwingFunction
did not return the string.
Look how much cleaner the code is in OptionalTryView
. Instead of do
and catch
blocks, along with handling the errors involved, I am simply setting the text if it’s possible.
There is an advantage to using do-catch when we have a variety of possible errors, but this is about the only time when it seems necessary.
Swift optionals are powerful, and try?
isn’t used enough as a way to cut down on unnecessary code in my opinion.