Skip to content
Tutorials Center
My learning

Topics

Lesson 78 of 146 ยท Error Handling

Assertions and Preconditions

Learn when to use assert, precondition, fatalError and Never in Swift, how they differ in debug and release builds, and when a crash is better than a thrown error.

Not every problem is an error you can recover from. If a caller passes a negative array size, or your own code reaches a branch you were sure could never run, there is nothing sensible to return and nothing useful to catch. The program has a bug, and the safest response is to stop right there, loudly, instead of limping on with corrupt data.

Swift gives you a small set of tools for this: assert, precondition, fatalError and the Never type. This lesson explains what each does, how they behave in different build modes, how to tell them from thrown errors, and how the Swift standard library itself uses them. You will also see what a real crash looks like in this runner.

Errors versus bugs

Two kinds of problems look similar but need different handling:

  • Expected failures come from the outside world: a missing file, bad user input, a network that is down. Your program should be able to cope. Use throws, an optional or a Result.
  • Programmer mistakes break an assumption your code relies on: an index that must be in range, a value that must not be empty, a state machine that must never reach "impossible". Callers cannot fix these at run time. The fix is to change the code. Use an assertion, a precondition or fatalError.

A good rule of thumb: if a user can cause it by typing something strange, it is an error. If only a bug can cause it, it is a broken assumption.

assert: a check for development

assert(condition, message) checks a condition and stops the program if it is false. The key point is that it only does this in debug builds. In optimized release builds the whole call is removed, and the condition is not even evaluated. The message is optional and is written as an autoclosure (see escaping closures and autoclosures), so it costs nothing when the assertion is off.

The compiler on this site builds with -O, the optimization level you use for release builds, so assertions are switched off here. This example shows that: the condition is false, yet the program carries on.

Swift assert does nothing in an optimized build

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

In a debug build (the default when you press Run in Xcode, or swift build without -c release), average([]) would stop with Assertion failed: average needs at least one number. In this runner the assertion is compiled away and the function returns 0. This is why you should never put code with side effects inside an assert:

Swift
// Bad: the removeLast() call vanishes in release builds
assert(items.removeLast() == "done")

Use assert for internal sanity checks that are useful while you build and test: "this list should be sorted at this point", "this index should be valid". It documents your assumptions and catches mistakes early, with zero cost in the shipped program.

There is a sibling, assertionFailure("message"), for a place you believe cannot be reached. It also does nothing in release builds.

precondition: a check that stays on

precondition(condition, message) looks just like assert but is kept in optimized builds. If the condition is false, the program stops. Use it to enforce a rule that callers must follow, where continuing would be unsafe or meaningless.

Swift precondition stops the program (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The grid prints as [[0, 0, 0], [0, 0, 0]], then about to break the rule appears, and the second call to makeGrid kills the program. Output printed before a crash is kept. In this runner a trap built with -O shows up as a crash signal (SIGILL) with a backtrace, and without the Fatal error text that a debug build would print. On a real machine in a debug build you would see the message Precondition failed: grid size must be positive together with the file and line.

The difference between the two checks comes down to who needs to be protected:

Function Debug build Release build (-O) Typical use
assert stops if false removed Internal sanity checks while developing
precondition stops if false stops if false Rules callers must obey
fatalError always stops always stops Unreachable code, missing required setup

In the unusual -Ounchecked mode preconditions are removed as well, and the compiler may assume they hold. Almost nobody uses that mode, but it is another reason to keep important checks in code that works, not in code that "can never happen".

fatalError: always stop

fatalError("message") ends the program unconditionally, in every build mode. It has the return type Never, which means "this function does not return", and so the compiler knows nothing after it can run. That lets you use it where a value is required but none can exist.

Swift fatalError in an impossible branch (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You see west and north, and then the crash. Unlike a trap from -O, fatalError prints its message on the error stream: binary/main.swift:21: Fatal error: unknown direction 'up', which includes the file and line, before the process ends with the same SIGILL crash and backtrace. The exit code is not zero, and the runner shows a note about it.

Notice that the default branch has no return statement, and the compiler does not complain. Because fatalError returns Never, control cannot continue past it, so the function does not need to produce a value on that path.

Writing fatalError() in a function body is the usual way to mark "not implemented yet" or "subclass must override". Treat it as a to-do that must be gone before release, not as a way to handle bad input.

Never: the type of "does not return"

Never is an enum with no cases, so a value of type Never can never exist. A function that returns Never therefore cannot return normally. It must crash, loop forever or exit the process. The standard library uses it in several places:

Swift Writing your own Never-returning function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler cannot prove that the three if statements cover every integer, so it would complain about a missing return at the end. Calling a function that returns Never tells it that the end of the function is not reachable. Note that this is a safety net: the unreachable call guards a branch that should truly never run.

Never is also useful in generic code. Result<Int, Never> is a result that cannot fail, and a throws(Never) function cannot throw (see typed throws).

Crashes the language gives you for free

You do not have to write every check yourself. Swift traps on many bugs automatically, and it does this in release builds too. These are all preconditions built into the language:

  • Force-unwrapping nil with !.
  • Reading an array index that does not exist.
  • Integer overflow with the plain operators (+, -, *).
  • A failed forced cast with as!.
  • try! on a call that throws.
Swift Array index out of range (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first three colors print, and then the program traps when index reaches 3. You will see the crash signal and a backtrace, not an error you can catch, and in this optimized build no message text at all. In a debug build the message reads Fatal error: Index out of range. The designers chose a crash over returning garbage, because reading beyond an array is almost always a bug and silent corruption is worse.

Overflow is the same story. Int.max + 1 traps; if you really want wrap-around arithmetic, ask for it with &+, and if you want to detect overflow, use addingReportingOverflow. See working with numbers.

Swift Choosing between a crash and a safe alternative

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Prefer these safe forms when a failure is a normal outcome. Keep the trapping forms (!, direct indexing, plain +) for situations where a failure really would mean your program is broken, and where crashing early is what you want.

When to crash and when to throw

How do you choose between throw and a precondition? Ask who is responsible for the failure and whether the caller can reasonably recover.

  • Throw when the failure depends on the outside world, or when the caller might want to handle it: parsing text, reading a file, a failed validation. Document the errors a function can throw.
  • Use precondition when you document a rule and a caller who breaks it has a bug. Example: Array(repeating:count:) requires a non-negative count.
  • Use assert for checks that help you while developing but whose cost or crash you do not want in production.
  • Use fatalError for code that should be impossible to reach, or for setup that must exist for the app to make sense at all.

A crash is also a feature in one sense: it produces a stack trace pointing at the first moment things went wrong. A program that quietly continues with a bad value tends to fail much later, far from the cause.

Never use a crash to handle input from users or other systems. A server that calls fatalError on a malformed request can be taken down by anyone who sends one. Validate untrusted input and respond with an error instead.

Writing helpful messages

A message turns a mystery crash into a quick diagnosis. Good messages say what was expected and, when cheap, what was found: "index \(i) out of range 0..<\(count)" is far better than "bad index". The message is an autoclosure, so building it is free on the happy path.

Swift also fills in the file and line automatically through #file and #line, so you do not have to mention where the check is. For more on diagnostics and these literals, see printing and debugging.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens to assert(x > 0) in an optimized release build?

    assert is a debug-only check. With optimization on, the call and its condition are removed.
  2. 2. Which check stays active in release builds and stops the program when its condition is false?

    precondition keeps checking in optimized builds, while assert and assertionFailure are removed.
  3. 3. Why can a function whose last statement is fatalError("...") omit a return value on that path?

    Never means the call does not return. The compiler knows the path ends there.
  4. 4. Why should you not call a function with side effects inside assert, such as assert(list.removeLast() == 0)?

    When assertions are off, the condition is not evaluated, so any work done inside it does not happen.
  5. 5. A user types "abc" where a number is expected. What is the right way to handle it?

    Bad input from outside is an expected failure, not a bug. Parse safely and report it, rather than crashing.

Summary

  • Use throwing functions, optionals or Result for expected failures; use assertions, preconditions and fatalError for broken assumptions (bugs).
  • assert and assertionFailure run only in debug builds; the condition is not evaluated in optimized builds, so keep side effects out of it.
  • precondition also checks in release builds and stops the program if the condition is false.
  • fatalError always stops and returns Never, so code after it is unreachable and no return value is needed.
  • Never has no values; functions returning it never return, and Result<T, Never> cannot fail.
  • Force unwraps, bad indices, overflow, as! and try! trap automatically; prefer safe alternatives (??, first, &+, addingReportingOverflow) when failure is normal.
  • Never crash on untrusted input; validate it and report an error.

Next: Introduction to Swift Concurrency