Assertion (assertions)
Optionals allows us to detect whether a value exists. In some cases, if a value does not exist or does not provide a specific satisfying condition, the code should not continue to execute down.
In these cases, you can use the trigger assertion to terminate execution and provide debugging.
The assertion is whether the condition is true at run time, and if true, continue down or it will be interrupted here.
assert that the corresponding keyword is assert
Such as:
- Let age = 18
- The result of the age >= 18 expression Here is true, so here's the assertion that nothing is done and the code continues to execute
- ASSERT (age >= 18, "a person ' a cannot is less than eighteen")
- Because the result of the age >= 22 expression is false, there is an interrupt here, which prints out
- "A person ' s age cannot is less than 22"
- ASSERT (Age > 22, "A person's age cannot is less than")
When do I use assertions?
Use assertions when the following conditions are included:
1. When an integer subscript index is passed as a value to a parameter implemented by a custom index, but the subscript index value cannot be too low or too high, use an assertion
2, pass the value to the function but if this pass-through value is invalid, the function cannot complete the function when the assertion is used.
3, the optional value is currently nil, but the following code successfully executes the condition is that the value cannot be nil, using assertions
Swift: Assertion (assertions)