Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to force a crash in Swift

What is the easiest way to force a crash in Swift?

I would like to use only one line of code (something that I can add quickly).

I don't want to use breakpoints, I actually want the app to crash.

like image 295
quemeful Avatar asked Sep 10 '15 20:09

quemeful


People also ask

How do you crash a swift code?

How to force a crash using fatalError() Swift has a built-in function called fatalError() , which forces your application to crash. This might sound useful, but bear with me – this is an indispensable function for anyone serious about writing good Swift.

What does fatalError do in Swift?

As the name implies, fatal errors are a type of error. They are typically thrown when the application enters an unknown or unexpected state. As a result, the behavior of the application becomes undefined. The behavior of the application becomes undefined.


2 Answers

Typically you'd use

fatalError() 

or

preconditionFailure() 

for that.

These do exactly the same: terminating the program, therefore the code after this stamement never gets executed. All of the functions that have this behaviour are annotated with the @noreturn attribute

You can also do something like this:

func getInt() -> Int {     fatalError() } 

The function is supposed to return an Int, but because the program never gets to that point, you don't have to return anything.

like image 155
Kametrixom Avatar answered Oct 08 '22 12:10

Kametrixom


[0][1] 

This tries to access second element of a one element array.

like image 28
quemeful Avatar answered Oct 08 '22 12:10

quemeful