Codementor Events

When to use try! in production Swift code?

Published Jan 22, 2019
When to use try! in production Swift code?

The short and easy answer to this question is never. However, there are actually some use cases where try! could be considered valid, even in production code.

When you use try! in your Swift code, you are ensuring that if the call it's being used with does throw, your application is going to immediately cease to run. Under the vast majority of circumstances this is the last thing that should ever happen. Your users are pretty much never going to be happy that your application crashed while they were using it, even if they didn’t experience data corruption or complete loss.

The only time it is considered acceptable to use try! in production code is when you are using a call that most definitely should never fail. The example used in the Swift documentation is when you are loading resources that ship with your app such as images. The idea is that if you use try!, you have decided that if your code were to crash at this point, it would be the least of your user's problems. At least in terms of using your app. In my mind it’s even questionable whether you should crash your app just because it is unable to load an image resource. However, to each his own.

Fortunately, Swift includes 3 other options available to you for error handling. All 3 of them allow you to handle thrown errors in a much more graceful way that will, at the very least, reduce the amount of friction your users experience while using your app.

You can find more information about Swift error handling at swift.org.

Discover and read more posts from Pat Garner
get started
post commentsBe the first to share your opinion
Show more replies