Easiest way to force a crash in Swift

24,405

Solution 1

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.

Solution 2

[0][1]

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

Solution 3

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

Solution 4

reversed ranges,

21...3

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

Share:
24,405
quemeful
Author by

quemeful

I turn coffee into code.

Updated on November 17, 2020

Comments

  • quemeful
    quemeful over 3 years

    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.

  • Libor Zapletal
    Libor Zapletal about 8 years
    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.
  • Kametrixom
    Kametrixom about 8 years
    @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
  • julien_c
    julien_c over 7 years
    [][0] is one character shorter 🤓
  • Peter DeWeese
    Peter DeWeese over 7 years
    Like the brevity, but it doesn't self document as well as fatalError().
  • Mustafa
    Mustafa about 4 years
    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.
  • Sazzad Hissain Khan
    Sazzad Hissain Khan over 3 years
    0/1 is three characters shorter 🤓
  • RemembranceNN
    RemembranceNN almost 3 years
    @SazzadHissainKhan 0/1 == 0 :-)
  • Sazzad Hissain Khan
    Sazzad Hissain Khan almost 3 years
    @RemembranceNN then compiler should be changed. That’s really a wrong output.
  • chadbag
    chadbag over 2 years
    @SazzadHissainKhan. why is 0/1 wrong output to output 0? I think you mean 1/0.