/ SWIFT

Difference Between Assert, Precondition and Fatal Error in Swift

Swift has three non-recoverable ways of dealing with errors: assert(), precondition() and 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 nil.

Since the three ways of failing are much alike, here is some rational to distinguish between them:

  • Use assert() to check your code for internal errors.
  • Use precondition() when consuming arguments from your clients. These parameters require public documentation.
  • Use fatalError() only in development when error is critical or you have nothing to return from a method. The latter is the case, since fatalError() returns 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.

Further Reading

Here I discuss different error handling strategies in depth: Swift Error Handling Strategies: Result, Throw, Assert, Precondition and FatalError.