Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the easiest way to make swift crash?

Tags:

swift

crash

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?

like image 633
Jan Rüegg Avatar asked Nov 30 '22 17:11

Jan Rüegg


1 Answers

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)
like image 146
Antonio Avatar answered Dec 10 '22 00:12

Antonio