ylliX - Online Advertising Network

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:

var myIntVar: Int = 42

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

myIntVar = nil 

is not possible. Now look at second example:

var myOptionalIntVar: Int? = 42

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

myOptionalIntVar = nil

Next example is:

var myAnotherOptionalIntVar: Int?

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:

if myAnotherOptionalIntVar != nil {
    print("myAnotherOptionalIntVar has value")
} else {
    print("myAnotherOptionalIntVar is nil")

You can also do it in Swifty way by:

if let myVar = myAnotherOptionalIntVar {
    print("myAnotherOptionalIntVar has value \(myVar)")
} else {
    print("myAnotherOptionalIntVar is nil")

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

if let myVar = myAnotherOptionalIntVar, let myInt = myOptionalIntVar {
    print("myAnotherOptionalIntVar has value \(myVar) and myOptionalIntVar has value \(myInt)")
} else {
    print("myAnotherOptionalIntVar or myOptionalIntVar are nil")

You can even validate your int by doing:

if let myVar = myAnotherOptionalIntVar, myVar > 10 {
    print("myAnotherOptionalIntVar has value \(myVar) and it's greater then 10")

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):

let myVar = myAnotherOptionalIntVar ?? 0

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