I would like to make swift crash, to test some crash handling functionality of my app.
In C++ I usually dereference a NULL pointer to do that, like so:
int *i = 0;
*i = 42;
What the easiest way to generate a crash in swift?
You can use the forced unwrapping operator on a nil optional variable:
let number: Int? = nil
let val = number!
That should throw an exception like this:
fatal error: unexpectedly found nil while unwrapping an Optional value
However you can also use a more elegant way to make your app crash, using the fatalError
global function, which stops the program execution - but it accepts some parameters that can be useful depending on what you are trying to achieve:
@noreturn func fatalError(@autoclosure message: () -> String = default, file: StaticString = default, line: UWord = default)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With