Swift: Do? There is no do. There is no do not. There is just try!

play-volleyball-4-1179000-m

As Yoda may not have put it, “try or try not, there is no do”. Although strictly speaking, there is a do. In fact, there’s quite a lot of do{} in Swift 2.0. At the same time, there’s also try. And, quite interestingly, there’s also try!.

You call throwing functions using the try or try! operators. Try! (known to its closest friends as try-with-an-exclamation-point) is the forced-try expression. It enables you to skip the do-catch-tango of doom handling.

Forced-try wraps your call in a runtime assertion made with the highest quality asserts lovingly crafted by artisan compilation and disables error propagation. In a nutshell, it throws a run-time error instead of passing errors to handlers for in-app resolution.

So why would you use this? Try! is for calls that throw but that you pretty much know a priori will never fail. As a rule, don’t try! unless you’re sure a throwing function isn’t going to throw.

Try! is also handy for quick playground hits where you just want something to run, and you don’t really care if it fails and crashes.

A forced-try basically says, “Just go ahead and perform this throwing operation and if it fails, so be it.”

Fun facts:

  • The throws keyword is automatically part of a function’s type. Non-throwing functions are subtypes of throwing functions. So you can use the try operator with non-throwing functions.
  • When currying the throws applies only to the innermost function.
  • You can’t override non-throwing methods with throwing ones but you can override a throwing method with a non-throwing method.
  • Throwing functions cannot satisfy protocol requirements for non-throwing functions but you can satisfy a throwing requirement with a non-throwing implementation.

Comments are closed.