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

Swift

Swift Problem Overview


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?

Swift Solutions


Solution 1 - Swift

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.

Solution 2 - Swift

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

Solution 3 - Swift

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.

Solution 4 - Swift

> 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

Solution 5 - Swift

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChao RuanView Question on Stackoverflow
Solution 1 - SwiftAirspeed VelocityView Answer on Stackoverflow
Solution 2 - Swiftonmyway133View Answer on Stackoverflow
Solution 3 - SwiftGregView Answer on Stackoverflow
Solution 4 - SwiftKeshav KumarView Answer on Stackoverflow
Solution 5 - SwiftAkshansh ThakurView Answer on Stackoverflow