[Swift] Termination of the program by the fatalError function

What is the fatalError function?

Optional \ type, Result \ <Success, Failure> type, do-catch statement, etc. There were various merits by writing error handling.

** First, reduce the chances of users encounter failures. Second, it is possible to inform the user of the details of the failure and prompt the return operation. ** ** Etc. are the main merits.

However, some errors are not supposed to occur in the first place, There are also errors ** where there is no way to recover because it is not expected.

In such cases, ** terminating the program is an option. ** **

One way to force the program is the fatalError () function.

** The fatalError () function It is a function to declare that the execution of that part is unexpected. ** **

Implementation method

The fatalError () function takes an exit message as an argument Executing the fatalError () function causes a run-time error and terminates the program.

As for the execution result, the source file name and line number are output in addition to the message specified by the argument.


fatalError("The program will be terminated because an unexpected error has occurred.")

Effective result
Fatal error:The program will be terminated because an unexpected error has occurred.: file __lldb_expr_369/MyPlayground.playground, line 2

Never type

The return value of the fatalError () function will be of type Never. The Never type is a special type that returns a ** value **.

When I hear that it doesn't return a value Is it similar to Void type? I think it doesn't mean that It means that ** the program is terminated when the function is executed, so no value is returned **.

When you execute a function that has a Never type as a return value, Since it is considered that the processing after that point is not executed, Eliminates the need to return a return value.

The usage of fatalError () is as follows. In the sample code below, a compile error does not occur even if the return value is not described.


func sample(value: Int) -> Int {
    fatalError("No return value is needed.")
}

If you make good use of this usage, ** No need to implement processing in unexpected situations. ** **

In the following sample code, medals will be passed according to the ranking. You can get medals from 1st to 3rd place, but not after 4th place.

Also, since the argument rank is an Int type, Unless otherwise specified in the Switch statement, it is necessary to cover Int type values.

For such a case, the values ​​other than the 1st, 2nd, and 3rd places are set as default. Define the fatalError () function in default.


func sample(rank: Int) -> String {
    switch rank {
    case 1:
        return "It is the first place. I will give you a gold medal."
    case 2:
        return "It is the second place. I will give you a silver medal."
    case 3:
        return "It is the third place. I will give you a bronze medal."
    default:
        fatalError("There are no medals after 4th place.")
    }
}

The fatalError () function can properly represent such an unexpected situation.

Usage timing

Terminate the program in unexpected situations

It's a little difficult to say in a word that it's an unexpected situation, ** If it is clear that you do not have to consider unexpected situations in implementation **, I think you can use the fatalError () function to terminate the program in unexpected situations.

On the contrary, ** when unexpected behavior can occur sufficiently, such as when it depends on external resources **, I think it is better to have an implementation that can continue execution.

It's short, but that's all for the fatalError () function!

Also, please have a look at the article about other error handling. -[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 assertion

Thank you for watching until the end.

Recommended Posts

[Swift] Termination of the program by the fatalError function
[Swift] Termination of the program by assertion
Image processing: The basic structure of the image read by the program
[Swift] I tried to implement the function of the vending machine
[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] How to implement the countdown function
[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
[swift5] How to implement the Twitter share function
[Swift] How to implement the fade-in / out function
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