Chao Ruan
Chao Ruan

Reputation: 1449

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

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?

Upvotes: 129

Views: 33246

Answers (6)

yoAlex5
yoAlex5

Reputation: 34195

iOS assert vs precondition vs fatal

General rule:

1. -O(-O, -Osize) - compile out(do not execute) `assert` and `assertionFailure`
2. -Ounchecked(as `SWIFT_OPTIMIZATION_LEVEL = -Ounchecked` or `SWIFT_DISABLE_SAFETY_CHECKS` = true) 
 2.1 set `condition: true` into `assert(condition: true)` and `precondition(condition: true)` that is why app is not terminated
 2.2 optimizer is free to assume that `assertionFailure` and `preconditionFailure` code are never called

Error looks like

Experiments2/ViewController.swift:20: Assertion failed: Some error
2022-12-11 15:17:28.772447+0200 Experiments2[95061:10414104] Experiments2/ViewController.swift:20: Assertion failed: Some error
  1. assert(condition: Bool, message: String)
  2. assertionFailure(message: String)
  3. precondition(condition: Bool, message: String)
  4. preconditionFailure(message: String) -> Never
  5. fatalError(message: String) -> Never

Never create build time warning

Will never be executed

[Optimization Level(SWIFT_OPTIMIZATION_LEVEL)]

  • -Onone - by default for app debug
  • -O - by default for app release
|                                   | -Onone    |                    -O                     |                 -O -Ounchecked                    |                   -Ounchecked                     |
|--------------------------------   |:------:   |:----------------------------------------: |:----------------------------------------------:   |:----------------------------------------------:   |
| assert(condition: false)          |  TRUE     |       FALSE -O (compile out assert)       |          FALSE -O (compile out assert)            |      FALSE -Ounchecked (condition == true)        |
| assertionFailure                  |  TRUE     | FALSE -O (compiled out assertionFailure)  |    FALSE  -O (compile out assertionFailure)       | TRUE or FALSE -Ounchecked(may never be called)    |
| precondition(condition: false)    |  TRUE     |                   TRUE                    |      FALSE -Ounchecked (condition == true)        |      FALSE -Ounchecked (condition == true)        |
| preconditionFailure               |  TRUE     |                   TRUE                    | TRUE or FALSE -Ounchecked(may never be called)    | TRUE or FALSE -Ounchecked(may never be called)    |
| fatalError                        |  TRUE     |                   TRUE                    |                      TRUE                         |                      TRUE                         |
TRUE - app is terminated
FALSE - app is not terminated

Upvotes: 0

Akshansh Thakur
Akshansh Thakur

Reputation: 5331

Just wanted to add my 2 cents. You can add as many assertions in your code as you want. You can Ship your code with these assertions. Swift does NOT evaluate these code blocks for production apps. These are only evaluated in case of debug mode.

Adding documentation link

Also attaching image from swift.org

enter image description here

Also note, this is not the case with preconditions. Code shipped with preconditions will crash and app will terminate if preconditions are not evaluated to be true.

So in short, assertions are for debugging, but can be shipped without impacting production. Assertions will be evaluated in debug mode but not in production.

And

PreConditions are for making sure unexpected things do not happen on production environment. Those conditions are evaluated and will terminate your app in case they're evaluated to be false

Upvotes: 1

onmyway133
onmyway133

Reputation: 48075

I found Swift asserts - the missing manual to be helpful

                        debug   release   release
function                -Onone  -O       -Ounchecked
assert()                YES     NO        NO
assertionFailure()      YES     NO        NO**
precondition()          YES     YES       NO
preconditionFailure()   YES     YES       YES**
fatalError()*           YES     YES       YES

And from Interesting discussions on Swift Evolution

– assert: checking your own code for internal errors

– precondition: for checking that your clients have given you valid arguments.

Also, you need to be careful on what to use, see assertionFailure and Optimization Level

Upvotes: 116

Airspeed Velocity
Airspeed Velocity

Reputation: 40955

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.

Upvotes: 136

Keshav
Keshav

Reputation: 1133

precondition

func precondition(condition: @autoclosure () -> Bool, _ message: @autoclosure () -> String = default, file: StaticString = default, line: UWord = default)

Check a necessary condition for making forward progress.

  1. Use this function to detect conditions that must prevent the program from proceeding even in shipping code.
  2. 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.
  3. In -O builds (the default for Xcode's Release configuration): if condition evaluates to false, stop program execution.
  4. 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

func assert(condition: @autoclosure () -> Bool, _ message: @autoclosure () -> String = default, file: StaticString = default, line: UWord = default)

Traditional C-style assert with an optional message.

  1. 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.

  2. 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.

  3. In -O builds (the default for Xcode's Release configuration), condition is not evaluated, and there are no effects
  4. 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 erro

Upvotes: 6

Greg
Greg

Reputation: 25459

The precondition is active in release mode so you when you ship your app and the precondition failed the app will terminate. Assert works just in debug mode as default.

I found this great explanation when to use it on NSHipster:

Assertions are a concept borrowed from classical logic. In logic, assertions are statements about propositions within a proof. In programming, assertions denote assumptions the programmer has made about the application at the place where they are declared.

When used in the capacity of preconditions and postconditions, which describe expectations about the state of the code at the beginning and end of execution of a method or function, assertions form a contract. Assertions can also be used to enforce conditions at run-time, in order to prevent execution when certain preconditions fail.

Upvotes: 20

Related Questions