Ios – Easiest way to force a crash in Swift

iosipadiphonemacosswift

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.

Best Answer

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.