Assertion
Optional allows you to infer whether a value exists, and you can gracefully handle the absence of a value in your code. However, in some cases, assuming that the value is missing or that the value does not meet a specific condition, your code may not need to continue executing. Then. You can trigger an assertion (assertion) in your code to end code execution and debug to find out why the value is missing.
Using Assertions for debugging
The assertion infers whether a logical condition is true at execution 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 executing other code. Assuming that the condition is inferred to be true, the code execution continues, and the assumption condition is inferred to be false. Code execution stopped. Your app has been terminated.
Suppose your code triggers an assertion in the debug environment, for example, when you build and execute an application in Xcode, you can clearly see where the illegal state occurs and check the state of your app when the assertion is triggered. Additionally, the assertion agrees that you 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:
Let-age = -3assert (age >= 0, "A person ' s agecannot is less than zero")//due to age < 0. So the assertion will trigger
In this example, the code execution will continue only if the age >= 0 is true, that is, when the value of age is not negative. Assuming that the value of age is negative, as in code, age >= 0 is false, the assertion is triggered, and the application ends.
Assertion information cannot use string interpolation.
Assertion information can be omitted. Just like this:
ASSERT (age >= 0)
When to use assertions
Use assertions when the condition may be false, but finally make sure that the condition is true so that your code can continue to execute.
Scenarios where assertions are applicable:
The subordinate script index of an integer is passed into a self-defined satellite script implementation. However, the subscript index value may be too small or too large.
You need to pass a value to the function. However, illegal values can cause the function to not execute properly.
An optional value is now nil. However, the subsequent code execution requires a non-nil value.
Please refer to the attached scripts and functions.
Attention:
Assertions can cause your app to terminate execution, 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 published, and using assertions can detect problems at high speed.
Swift programming language Learning 1.7--assertions