In Swift, what do `assert`, `precondition` and `fatalError` each do in `-Onone`, `-O` and `-Ounchecked` builds?
answer
- Debug vs Release defaults
- which check survives Release
- which one stops in every build
- the optimizer may assume it holds
- autoclosure conditions and side effects
basics
~20 sassert checks only in -Onone (Debug) builds; precondition checks in -Onone and -O, so it traps in Release too; fatalError stops the program in every build. In -Ounchecked, assert and precondition are not evaluated and the optimizer may assume they hold.
solid answer
~40 s`assert(_:_:file:line:)` is an internal sanity check: in `-Onone`, Xcode's Debug default, a false condition prints the message and stops; in `-O`, the Release default, the condition is not evaluated at all. `precondition(_:_:file:line:)` guards a contract the caller must meet and stays in `-O`, where it traps without printing your message. `fatalError(_:file:line:)` returns `Never` and stops the program in every build, `-Ounchecked` included, so it suits code that must never run. `assertionFailure` and `preconditionFailure` are the unconditional forms of the first two and follow the same per-build rules. In `-Ounchecked`, `assert` and `precondition` are not evaluated and the optimizer may assume they hold, so a violation is undefined behaviour rather than a crash. Because each condition is an `@autoclosure`, side effects inside an `assert` disappear from Release builds.
code
swift · 25 linesstruct Config {
let poolSize: Int
let environment: String
}
func makeConfig(poolSize: Int, environment: String) -> Config {
// Debug-only sanity check: not evaluated in -O
assert(poolSize < 1_000, "suspicious pool size \(poolSize)")
// Caller contract: checked in -Onone and -O, not in -Ounchecked
precondition(poolSize > 0, "poolSize must be positive")
return Config(poolSize: poolSize, environment: environment)
}
func baseURL(for config: Config) -> String {
switch config.environment {
case "staging": return "https://staging.example.com"
case "production": return "https://api.example.com"
default:
// Stops the program in every build, -Ounchecked included
fatalError("unknown environment \(config.environment)")
}
}
let config = makeConfig(poolSize: 0, environment: "production")
print(baseURL(for: config))go deeper
Remember the headline: assert is Debug-only, precondition also runs in Release, and fatalError always stops the program.
Walk through the three optimization levels for each function, including the silent trap in -O and the autoclosure that removes side effects from assert.
Pick the right check for each invariant in real code, explain a messageless Release crash, and argue why -Ounchecked turns violations into undefined behaviour.
Decide which invariants a team checks in shipping builds, what that costs in crash rate versus corrupted state, and whether any target may use -Ounchecked.
## Three build configurations Swift's checking functions read the **optimization level** the code was compiled with: - **`-Onone`**: no optimization; the default for Xcode's **Debug** configuration and for playgrounds. - **`-O`**: optimized; the default for Xcode's **Release** configuration. - **`-Ounchecked`**: optimized with many runtime checks removed; a deliberate opt-in, not a default. (`-Osize` and the cost model of each level are covered with compiler optimization; here only their effect on the checks matters.) ## What each function does | Function | `-Onone` | `-O` | `-Ounchecked` | |---|---|---|---| | `assert(cond, msg)` | evaluates; on false prints the message and stops | condition **not evaluated**, no effect | not evaluated; optimizer may assume it is true | | `assertionFailure(msg)` | prints and stops | **no effect** | optimizer may assume it is never called | | `precondition(cond, msg)` | evaluates; on false prints and stops | evaluates; on false **traps, message not printed** | not evaluated; optimizer may assume it is true | | `preconditionFailure(msg)` | prints and stops | traps | optimizer may assume it is never called | | `fatalError(msg)` | prints and stops | **prints and stops** | **prints and stops** | All of this comes from the doc comments in the standard library's `Assert.swift`, and a compiled run of the example confirms it. Note the quiet detail in the `-O` column: `precondition` still stops the program, but your message string is not printed. The crash report's stack trace, not the message, is what tells you where it failed. ## `assert` and `assertionFailure`: development-time checks The standard library describes `assert` as being for "internal consistency checks that are active during testing but do not impact performance of shipping code." Use it for invariants you believe hold and want verified while developing, especially when the check is expensive. Its condition and message are **`@autoclosure`** parameters. In `-O` the closure is never called, so: 1. any side effect written inside the condition, such as `assert(cache.purgeExpired() > 0)`, never happens in Release; 2. the cost of the check vanishes too, which is the point. ## `precondition` and `preconditionFailure`: contracts that ship `precondition` is for "conditions that must prevent the program from proceeding, even in shipping code": a caller passing a negative pool size, an index outside a range you document. The standard library uses an internal equivalent for its own contracts, which is why `removeFirst()` on an empty array traps in Release builds too. `preconditionFailure` is the unconditional form, documented for control flow that can only be reached through misuse, such as a `default` branch you know cannot be taken. It returns `Never`, so the compiler accepts it where a value would otherwise be required. ## `fatalError`: stops in every build `fatalError` is unconditional and keeps its behaviour in every optimization level, `-Ounchecked` included. Use it where continuing is impossible and where an optimizer assumption would be dangerous: an unknown configuration environment, a required subclass override, an `init(coder:)` you do not support. ## `-Ounchecked` is undefined behaviour, not silence In `-Ounchecked`, the doc comments say the optimizer "may assume" an `assert` or `precondition` condition is true, and that `assertionFailure` and `preconditionFailure` are never called. "Failure to satisfy that assumption is a serious programming error." This does not mean "the check is skipped and the program carries on safely". In one compiled test, an `-Ounchecked` build ran past an `assertionFailure` and straight into an unrelated `switch` branch. Treat a violated check in that mode as **undefined behaviour**. ## Choosing among them - A bug you want caught in development, and the check is expensive: `assert`. - A contract whose violation must never run on in production: `precondition`. - Code that must stop even under `-Ounchecked`: `fatalError`. - Anything caused by input, network or disk: none of these. That is a recoverable error, so throw it or return a `Result`. A useful habit is to write the message for the person who will read the crash: name the value that broke the contract, as in `precondition(poolSize > 0, "poolSize must be positive, got \(poolSize)")`. The message costs nothing in `-O` builds: it is an autoclosure, and `precondition` calls it only in `-Onone`, when the check fails.
- Why is `assert(cache.purgeExpired() > 0)` a bug?`assert`'s condition is an `@autoclosure` that is not evaluated in `-O` builds, so in Release `purgeExpired()` never runs and the cache is never purged. Do the work first and assert on the stored result: `let purged = cache.purgeExpired(); assert(purged > 0)`.
- In an exhaustive-in-practice `default:` branch, when would you pick `fatalError` over `preconditionFailure`?Both return `Never` and both stop in `-Onone` and `-O`. The difference is `-Ounchecked`: there the optimizer may assume `preconditionFailure` is never called, while `fatalError` still prints and stops. Pick `fatalError` when the branch must stop under every optimization level; `preconditionFailure` when you want the documented misuse check and accept the unchecked-build assumption.
- Your Release crash report shows a `precondition` trap but no message. Why?In `-O` builds `precondition` traps without printing its message; only `-Onone` prints it. The crash report's stack trace gives the failing frame. If the context matters in production, log it before the check, or use `fatalError`, which prints its message in every build.
- assert still runs in Release builds and just skips printing the message.
- precondition is compiled out of Release builds, just like assert.
- fatalError is removed when the app is built with -O.
- Under -Ounchecked a failed precondition is safely skipped and the program carries on.
- A side effect inside an assert condition runs in every build.