Difference between "precondition" and "assert" in swift?

swift

Solution

`assert` is for sanity checks during testing, whereas `precondition` is for guarding against things that, if they happen, would mean your program just could not reasonably proceed.

So for example, you might put an `assert` on some calculation having sensible results (within some bounds, say), to quickly find if you have a bug. But you wouldn’t want to ship with that, since the out-of-bound result might be valid, and not critical so shouldn’t crash your app (suppose you were just using it to display progress in a progress bar).

On the other hand, checking that a subscript on an array is valid when fetching an element is a `precondition`. There is no reasonable next action for the array object to take when asked for an invalid subscript, since it must return a non-optional value.

Full text from the docs (try option-clicking `assert` and `precondition` in Xcode):

Precondition

Check a necessary condition for making forward progress.

Use this function to detect conditions that must prevent the program from proceeding even in shipping code.

In playgrounds and -Onone builds (the default for Xcode's Debug configuration): if `condition` evaluates to false, stop program execution in a debuggable state after printing `message`.

In -O builds (the default for Xcode's Release configuration): if `condition` evaluates to false, stop program execution.

In -Ounchecked builds, `condition` is not evaluated, but the optimizer may assume that it would evaluate to `true`. Failure to satisfy that assumption in -Ounchecked builds is a serious programming error.

Assert

Traditional C-style assert with an optional message.

Use this function for internal sanity checks that are active during testing but do not impact performance of shipping code. To check for invalid usage in Release builds; see `precondition`.

In playgrounds and -Onone builds (the default for Xcode's Debug configuration): if `condition` evaluates to false, stop program execution in a debuggable state after printing `message`.

In -O builds (the default for Xcode's Release configuration), `condition` is not evaluated, and there are no effects.

In -Ounchecked builds, `condition` is not evaluated, but the optimizer may assume that it would evaluate to `true`. Failure to satisfy that assumption in -Ounchecked builds is a serious programming error.

Problem

What's the difference between `precondition(condition: Bool, message: String)` and `assert(condition: Bool, message: String)` in Swift? Both of them look same to me. In which context should we use one over the other?

Original source

Related problems