Optional allows you to determine if a value exists, and you can gracefully handle the absence of a value in your code. However, in some cases, if the value is missing or the value does not meet a specific condition, your code may not need to proceed. At this point, you can trigger an assertion (assertion) in your code to end the code run and debug to find the reason for the missing value .
using assertions for debugging
The assertion determines whether a logical condition is true at run time. In the literal sense, the assertion "asserts" whether a condition is true. You can use assertions to ensure that some important conditions have been met before running other code . If the condition evaluates to true, the code will continue to run, and if the condition evaluates to False, the code is stopped and your app is terminated.
If your code triggers an assertion in the debug environment, such as when you build and run an app in Xcode, you can clearly see where the illegal state occurs and check the state of your app when the assertion is triggered. Additionally, assertions allow you to attach a debug message.
You can use the global assert function to write an assertion. An expression with a result of true or false is passed to the Assert function, and a message is displayed when the expression is false:
In this case, only the age >= 0 is true when the code is run to continue, that is, when the value of age is not negative. If the value of age is negative, as in the code, age >= 0 is false, the assertion is triggered, and the app ends.
Assertion information cannot use string interpolation. The assertion information can be omitted, just like this:
when to use assertions
Use assertions when the condition may be false, but ultimately make sure that the condition is true so that your code can continue to run. Scenarios where assertions are applicable:
- The subordinate script index of an integer is passed into a custom satellite script implementation, but the subscript index value may be too small or too large.
- You need to pass in a value to the function, but an illegal value may cause the function to not execute properly.
- An optional value is now nil, but a non-nil value is required for the subsequent code to run.
Please referencing satellite scripts and functions .
Note: Assertions can cause your app to stop running, so you should design your code carefully so that illegal conditions do not appear. However, there are times when illegal conditions may occur before your app is released, and using assertions can quickly identify problems.
Zhao Yazhi _swift (4) _ Assertion