Try the new try?

With the new Xcode 7 beta 6 that was released earlier this week, Apple introduced the new try?  keyword. It gives us some more flexibility when handling operations that may throw errors.

Previusly, if you weren’t interested in the error, you still had to catch it.

You didn’t have to do anything in the catch block, but it made the intent of the code less clear. Did the developer forget to finish this implementation or was it intentional?

The only other option was to use try!  which let you omit the catching but crashed if it threw. Therefore try!  should only be used if you are certain that it won’t throw an error.

 

This would be fine if you are loading a file from your own bundle that you know exists. You should always be careful when using try! .

Have you tried to try?

The new try?  keyword lets us call operations that might throw and if it succeeds it will wrap up the results in an optional. If it fails however, then it will just be nil . It is particularly useful together with the if let  statement and the new guard  statement introduced in Swift 2.0.

In this case we are not interested in any error that might get thrown, only if it works or not.

This code does essentially the same thing as the previous example but uses the guard  statement instead. What these two examples show, boils down to a little bit cleaner code while maintaining safety.

If you haven’t tried guard  yet, I recommend reading this article that explains it well: http://ericcerney.com/swift-guard-statement/

Keep in mind

try?  statements always adds an extra layer of optionals. This means that if the return type of an operation that might throw is String? , the resulting type of calling that method with try? will be String??  or Optional<Optional<String>>

The code above could be compressed down to even more readable code by chaining the expressions in the guard statement like this:

That’s about it, there’s not much more to it. This will definitely let me write cleaner code. I hope it will be of great use to you too!

Petar Mataic

Petar is an ambitious young developer who hungers for new technology. Because new technology often means that his work becomes easier and allow him to do things faster, better, cooler. Experienced in .NET, he is currently focused on the iOS platform. Born in a country that doesn't exist anymore, he aspires to make the whole world his home, sharing his passion with other software developers attending and speaking at international conferences.

Leave a Reply

Close Menu