Chapter    12

Assertions

Assertions are a tool that you can use to help with your debugging efforts. Assertions work by testing a condition to see whether the condition is satisfied. If the condition is not satisfied, then a runtime error occurs, and the program stops executing. Assertions may have an optional message that is printed in the console window when the condition is not met.

To create an assertion, write the assertion shown in Listing 12-1.

Listing 12-1. Assert

var triangleSides = 4assert(triangleSides == 3, "A triangle must have three sides")

The assert statement in Listing 12-1 is testing to make sure that the triangleSides variable has the correct number of sides. If triangleSides has three sides, nothing happens. If triangleSides ...

Get Swift Quick Syntax Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.