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.
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
Related concepts
→
Assertions and Preconditions
→
Semantic portal