Basics: Assertions and Preconditions

You use them to make sure an essential condition is satisfied before executing any further code.

You use assertions and preconditions to express the assumptions you make and the expectations you have while coding, so you can include them as part of your code.

Are checks that happen at runtime.

A useful form of documentation within the code.

Debugging with Assertions

Let age = -3
assert(age >= 0, "A person's age can't be less than zero.")
// This assertion fails because -3 is not >= 0
If age > 10 {
    print("You can ride the roller-coaster or the ferris wheel.")
} else if age >= 0 {
    print("You can ride the ferris wheel.")
} else {
    assertionFailure("A person's age can't be less than zero.")
}

Additional information

  • You write an assertion by calling the assert(_:_:file:line:) function from the Swift standard library. You pass this function an expression that evaluates to true or false and a message to display if the result of the condition is false. .
  • If the code already checks the condition, you use the assertionFailure(_:file:line:) function to indicate that an assertion has failed.

Enforcing Preconditions

Use a precondition whenever a condition has the potential to be false, but must definitely be true for your code to continue execution.

// In the implementation of a subscript...
precondition(index > 0, "Index must be greater than zero.")

Additional information

  • You write a precondition by calling the precondition(_:_:file:line:) function. You pass this function an expression that evaluates to true or false and a message to display if the result of the condition is false.

Basics: Assertions and Preconditions — Structure map

Clickable & Draggable!

Basics: Assertions and Preconditions — Related pages: