[Swift] Termination of the program by assertion

What is an assertion?

Assertions are ** features that describe the conditions that a program must meet at some point. ** ** If the conditions are not met, the program execution will be interrupted.

The assertion causes a run-time error and terminates the program. ** Run-time errors occur only during debugging. ** **

At the time of release, processing continues regardless of the success or failure of the conditional expression. Isn't it quite convenient for me personally? I think.

Implementation method

Use the standard library assert () and assertionFailure () functions.

assert () function

The assert () function ** A function for declaring the conditions that should be met when this function is executed. ** ** If the conditions are not met when this function is executed, a run-time error will occur.

The first argument of the assert () function is a conditional expression, and the second argument is the message at the end.

** If the conditional expression is true, continue the subsequent processing and continue. If false, the message, file name, and line number passed as the second argument are output. ** **


let a = 10
let b = 11
assert(a == b, "The values ​​of a and b are different.")

Execution result
Assertion failed:The values ​​of a and b are different.: file __lldb_expr_383/MyPlayground.playground, line 5

assertionFailure () function

The assertionFailure () function is an assertion that always fails with no ** conditional expression. ** **

Because the execution itself does not meet the conditions ** Similar to the assert () function with false as the first argument. ** **

In the following sample code The season is output based on the value passed to the argument.

A run-time error will occur if there is no corresponding season for the passed value.


func printSeason(month: Int) {
    switch month {
    case 1...2, 12:
        print("winter")
    case 3...5:
        print("spring")
    case 6...8:
        print("summer")
    case 9...11:
        print("autumn")
    default:
        assertionFailure("Set a value from 1 to 12.")
    }
}

printSeason(month: 1)
printSeason(month: 10)
printSeason(month: 100)

Execution result
winter
autumn
Fatal error:Set a value from 1 to 12.: file __lldb_expr_385/MyPlayground.playground, line 13

Usage timing

Detect unexpected situations when debugging

By declaring the range of values ​​that the function expects using assertions, You can detect unexpected values ​​when debugging.

When the program continues to be executed even in unexpected situations at the time of release

Unlike the fatalError () function, which terminates the program even at release time At the time of release, the assertion will continue to execute the program even in unexpected situations.

** In other words, it decides whether to continue or interrupt the process when an unexpected situation occurs. ** **

The above is also an explanation of assertions.

Assertions and fatalError () are not common and It's not that difficult, so I think it's enough to put it in the corner of your head!

I also have an article about other error handling, so please have a look. -[Swift] Perform error handling with Optional \ type -[Swift] Perform error handling with Result \ <Success, Failure> type -[Swift] Perform error handling with do-catch statement (Part 1) -[Swift] Termination of program by fatalError function

Thank you for watching until the end.

Recommended Posts

[Swift] Termination of the program by assertion
[Swift] Termination of the program by the fatalError function
Image processing: The basic structure of the image read by the program
[Swift] Change the textColor of UIDatePicker
The basic basis of Swift dialogs
Order of processing in the program
[Swift] Vaguely grasp the flow of Delegate
The process of understanding Gemfile by non-engineers
[Swift] Get the height of Safe Area
[Swift] Change the color of SCN Node
The contents of the data saved by CarrierWave.
The basic basis of Swift custom cells
A review of the code used by rails beginners
[Swift] Get the number of steps with CMP edometer
Format of the log output by Tomcat itself in Tomcat 8
[Kotlin] Get the argument name of the constructor by reflection
[Swift] This is the solution! Illustration of Delegate implementation
Find the approximate value of log (1 + x) in Swift
[Swift] What I found by using the static property (static)
[Swift] How to get the document ID of Firebase
The world of clara-rules (2)
Judgment of the calendar
The world of clara-rules (4)
The world of clara-rules (1)
The world of clara-rules (3)
The world of clara-rules (5)
The idea of quicksort
The idea of jQuery
[Enum] Let's improve the readability of data by using rails enum
About truncation by the number of bytes of String on Android
[Rails] Register by attribute of the same model using Devise
Get the object name of the instance created by the new operator
Now, I understand the coordinate transformation method of UIView (Swift)
Install by specifying the version of Django in the Docker environment
When using the constructor of Java's Date class, the date advances by 1900.
[Swift] Lightly introduce the logic of the app that passed the selection
Get only the ID of the container specified by docker ps
Traps brought about by the default implementation of the Java 8 interface
[Rails] How to display the list of posts by category
Extending the four-tier model of the architecture proposed by Eric Evans
A program that counts the number of words in a List
Summary of values returned by the Spliterator characteristics method #java
[Swift] Get the timing when the value of textField is changed
Extract the uniquely identifying value of the table created by PostgreSQL