Assertions and Preconditions in Swift

Assertions and preconditions help us create checks for validating the program during runtime.  In general we use assertion to test whether our assumptions at specific stages of code execution is true or false for the program to continue execution. The assumptions may or may not be valid. Precondition is preferred when the assumption/condition to be tested must be true for the program to continue execution but it can be false due to some other reason. We can have as many assertions as possible in a program as they are tested only during debug build but preconditions are tested both in production and debug build.

Syntax:

assert(_condtion to be tested, “_message to be displayed”)

assertionFailure(“_message to be displayed”)

precondition(_condition to be tested, “_message to be displayed”)

preconditionFailure(“_message to be displayed”)

Sample Code:

Assertion and precondition

Leave a Reply