Assertions based on Swift

Optional allows you to determine whether the value exists, and you can gracefully handle missing values ​​in the code. However, in some cases, if the value is missing or the value does not meet certain conditions, your code may not need to continue execution. At this time, you can trigger an assertion in your code to end the code execution and debug to find the reason for the missing value.

One: Use assertions for debugging

Assertions will determine whether a logical condition is true at runtime. Literally speaking, an assertion "asserts" whether a condition is true. You can use assertions to ensure that certain important conditions have been met before running other code. If the condition is judged to be true, the code execution will continue; if the condition is judged to be false, the code execution stops and your application is terminated.

If your code triggers an assertion in a debugging environment, for example, you build and run an application in Xcode, you can clearly see where the illegal state occurs and check the state of your application when the assertion is triggered. In addition, assertions allow you to attach a piece of debugging information.

You can use the global assert function to write an assertion. Pass an expression with a result of true or false and a message to the assert function. This message will be displayed when the expression is false:

let age = -3
assert(age >= 0, "A person is age cannot be less than zero")
// 因为 age < 0, 所以断言会触发

In this example, the code execution will only continue when age >= 0 is true, that is, when the value of age is non-negative. If the value of age is negative, as in the code, age >= 0 is false, the assertion is triggered and the application ends.

Assertion information cannot use string interpolation. Assertion information can be omitted, like this:

assert( age > = 0)

Two: When to use assertions

Use assertions when the condition may be false, but in the end you must ensure that the condition is true so that your code can continue to run. The applicable scenarios of the assertion:

  • The integer satellite script index is passed into a custom satellite script implementation, but the subscript index value may be too small or too large.
  • You need to pass a value to the function, but an illegal value may cause the function to fail to execute normally.
  • An optional value is now nil, but subsequent code runs require a non-nil value.

Note : Assertions may cause your application to terminate, so you should carefully design your code to prevent illegal conditions from appearing. However, before your application is released, sometimes illegal conditions may appear, and then using assertions can quickly find problems.

Welcome to follow the official account [Swift Community]:

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_36478920/article/details/105813691