Swift has three non-recoverable ways of dealing with errors:
fatalError(). You should use be using of them, when an unexpected condition happens as a result of programmer mistake. Such mistakes must be fixed in code, instead of recovering from they, say, by throwing an error or returning
Since the three ways of failing are much alike, here is some rational to distinguish between them:
assert()to check your code for internal errors.
precondition()when consuming arguments from your clients. These parameters require public documentation.
fatalError()only in development when error is critical or you have nothing to return from a method. The latter is the case, since
Never. You never want your app to shut down unconditionally in production, therefore I recommend against shipping such code to real users.
Assertions are active only in debug build and are ignored in release. Therefore, you must provide a fallback for production. I suggest sending logs to your crash reporting system, so that you can fix the error in your next release.
Here I discuss different error handling strategies in depth: Swift Error Handling Strategies: Result, Throw, Assert, Precondition and FatalError.
Thanks for reading!
If you enjoyed this post, be sure to follow me on Twitter to keep up with the new content. There I write daily on iOS development, programming, and Swift.