41

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.

quemeful
  • 9,542
  • 4
  • 60
  • 69

6 Answers6

112

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.

Kametrixom
  • 14,673
  • 7
  • 45
  • 62
  • Could this be in release app? Will it goes through a certification process? I mean of course app can't crash during the process but for me it just checks for exact date (after 2 months from now) and then fatalError is called. – Libor Zapletal Apr 15 '16 at 10:26
  • @LiborZapletal You app has to not crash a lot to get accepted, it's better to handle errors when they occur. Your app should only crash when something went terribly wrong – Kametrixom Apr 15 '16 at 10:30
42
[0][1]

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

quemeful
  • 9,542
  • 4
  • 60
  • 69
4

You can simply try to access an optional value that has nil value... if you already have a variable declared and it is an optional, just call it (don't forget to unwrap) and it will crash for sure

Agustin
  • 166
  • 1
  • 11
3

reversed ranges,

21...3

Thread 1: Fatal error: Can't form Range with upperBound < lowerBound

black_pearl
  • 2,549
  • 1
  • 23
  • 36
1

If you have an integer variable, you can multiply it by the integer limit. (Similar method for UInt)

Poli Swag
  • 11
  • 1
1
import Darwin

exit(0)

The C library function void exit(int status) terminates the calling process immediately. Any open file descriptors belonging to the process are closed and any children of the process are inherited by process 1, init, and the process parent is sent a SIGCHLD signal.


1/0

    var a = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        _ = 1/a
dengApro
  • 3,848
  • 2
  • 27
  • 41
  • 1
    While this code may answer the question, it would be better to include some context, explaining how it works and when to use it. Code-only answers are not useful in the long run. – Mustafa Apr 22 '20 at 02:13