Fatal error: unexpectedly found nil while unwrapping an Optional value

This can be really painful when you just started with Swift. It really happens very often and can be confusing. Where it comes from?

In Swift “optional” can be any variable. By optional, Swift means – it can have a value, but it can also be nil. It is defined by “?” sign at end of declaration. Look at this:

Is it optional? No. We declared “myIntVar” as not optional, it has initial value and operation like:

is not possible. Now look at second example:

What we have here? We declared “myOptionalIntVar” as optional with initial value. Now you can do:

Next example is:

So what happens here? We declared “myAnotherOptionalIntVar” as optional, but without assigning any value so currently it will be nil.

How to handle safely optionals?

You can do it old way, and just check for nil, like this:

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

You can also do it in Swifty way by:

There is even more Swifty way, where you can check for many variables at once by:

You can even validate your int by doing:

There is also minimalistic way for this, so in case your “myAnotherOptionalIntVar” will be nil, new variable will be initialized with 0 value (and its called Nil Coalescing Operator):

So where our fatal error comes from?

The easiest way to see it is just:

Because if “myAnotherOptionalIntVar” won’t be initialized, your code will crash here.

You can grab Swift 3 playground to test those cases here https://github.com/blastar/Swift3OptionalsPlayground

Leave a Reply