Assertions and Preconditions: 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.

Related concepts

Assertions and Preconditions: Debugging with Assertions — Structure map

Clickable & Draggable!

Assertions and Preconditions: Debugging with Assertions — Related pages: