Explanation & Solution for 'fatal error: unexpectedly found nil while unwrapping an Optional value'

fatal error: unexpectedly found nil while unwrapping an Optional value

This is a super common error you’ll encounter when developing in Swift. We’ll explain the solution and why this happens in this article.

What Does Unexpectedly Found Nil While Unwrapping An Optional Value Mean

This error occurs when you unwrap an Optional with a nil value. This usually happens when you use the ! operator.

What Are Optionals

To understand this error, we first must understand what Optionals in Swift are. Optionals are a special generic type in the Swift Programming language. They are can contain a value or no value.

When an optional has no value, it is considered nil. You can declare an optional by using the question mark ? after the type.

For example:

var mightBeNil: String?

In the case above mightBeNil can either contain a string or no value (nil). Optionals can be of any type. Here are some more examples:

var optionalInt: Int?
var optionalCustomClass: CustomClass?
var optionalBool: Bool?
var optionalDouble: Double?

Now that we know what optionals are, let’s find out how unexpectedly found nil occurs.

Force Unwrapping Optionals

Force unwrapping optionals is the reason why this error happens, almost 99% of the time. Let’s take a look at a case that works and another one that doesn’t.

var greeting: String?
greeting = "Hello and welcome"
print(greeting! + " friend")

The above block of code works fine and will print “Hello and welcome friend” to your console. Try running this code instead, removing the middle line where we set the variable.

var greeting: String?
print(greeting! + " friend")

Xcode will print this out in console:

Fatal error: Unexpectedly found nil while unwrapping an Optional value

In order to access the greeting variable, we decided to forcefully unwrap it (with the ! operator). You can’t add a nil and a String type together, strings can only be added with other strings.

Since the greeting variable has no value assigned to it and is nil, Xcode will throw this error when trying to add greeting! and ” friend”.

Implicitly Unwrapped Optionals

This is the other way this error can occur. This happens often with IBOutlets, since they’re usually implicitly unwrapped optionals.

Implicitly unwrapped optionals are defined with a ! operator after their type:

var greeting: String!

These optionals are assumed to always contain a value. When you access an implicitly unwrapped optional, it will be forced unwrapped automatically.

So if we do:

var greeting: String!
print(greeting + " friend")

We’ll see our error again. You should try to avoid implicitly unwrapped optionals as much as you can.

Why Use Optionals

This seems confusing! Why do we need optionals anyways? Why can’t we just get rid of them entirely? We need optionals as there are times in your code where certain variables simply have no value at a given time. For example:

  • Accessing dictionary values such as person["address"], the key address may not have a value assigned to it yet.
  • User input variables, before the user has entered their information
  • Variables that are going to be set by an API call, before the API call has completed.

There are many other reasons why you would need optionals. Every language has some form of a nil variable, in Java its called null. The problem with other languages is that they crash at runtime when a nil value is found. Optionals help us catch these bugs at compile time, preventing a crash. They force the developer to think and unwrap the variable every time.

So why do these crashes still happen in Swift? Why aren’t they caught by the compiler? It’s because the two methods mentioned above: Force Unwrapping (!) and Implicitly Unwrapped Optionals can’t be caught by the compiler.

You should try avoid force unwrapping and implicitly unwrapped optionals as much as you can. Let’s learn how to use optionals correctly and safely.

How To Safely Unwrap Optionals

You could do it by checking for nil, like in many other languages. For example:

var greeting: String?
if greeting != nil {
    print(greeting! + " friend")
}

However, this still involves force unwrapping and using the ! operator. A more Swift approach would be to use optional binding.

Optional Binding

Optional binding checks first if the optional has a value and if it does, assigns it to a non-optional constant. This pattern is used quite often in Swift development.

Here’s an example:

var greeting: String?
if let unwrappedGreeting = greeting {
    print(unwrappedGreeting + " friend")
} else {
    print("greeting has no value!")
}

Notice in this pattern we don’t use any force unwraps (!). You can also chain this together with multiple optionals:

var greeting: String?
var friendsName: String?
if let unwrappedGreeting = greeting, let unwrappedFriendsName = friendsName {
    print(unwrappedGreeting + " " + unwrappedFriendsName)
} else {
    print("greeting or friend has no value!")
}

This above code will print greeting or friend has no value!. However, if we assign values to both of those valuables like so:

var greeting: String? = "Hey"
var friendsName: String? = "Eddie"
if let unwrappedGreeting = greeting, let unwrappedFriendsName = friendsName {
    print(unwrappedGreeting + " " + unwrappedFriendsName)
} else {
    print("greeting or friend has no value!")
}

It will print:

Hey Eddie

Guard Statements

What if you want to use this variable outside of an if statement? Do you have to continually wrap it in if statements? Nope! There’s a better solution, it’s called a guard statement.

Guard statements define a condition for the code to continue, otherwise it must return. You can use this in combination with optional binding like so:

printGreeting()

func printGreeting() {
    var greeting: String?
    var friendsName: String?

    guard let unwrappedGreeting = greeting, let unwrappedFriendsName = friendsName else {
        print("greeting or friend has no value!")
        return
    }

    print(unwrappedGreeting + " " + unwrappedFriendsName)
}

I use guard statements quite frequently when I’m writing Swift code.

Nil Coalescing Operator

The nil coalescing operator is shorthand if statement. It lets you define a default value if the optional contains nil.

var greeting: String?
var friendsName: String?

print((greeting ?? "Hi") + " " + (friendsName ?? "friend"))

In our above example, if no value is provided for greeting or friend, it will print the “Hi friend”.

Optional Chaining

Optional chaining lets you access a property or a function of an optional by simply using the ? operator.

For example, if you call uppercased() on a String:

var str: String?
str?.uppercased()

Even though str is nil in the above example, your code will not crash. It will simply not make that function call to uppercased() if str is nil.

Of course, you can chain these together, let’s pretend that middleName is an optional property of an optional person variable and that we’d like to get the uppercase string of that.

person?.middleName?.uppercased()

Optional chaining can make your code cleaner and remove the need for complicated if statement structures.

If you liked this post and want to learn more, check out The Complete iOS Developer Bootcamp. Speed up your learning curve - hundreds of students have already joined. Thanks for reading!

Eddy Chung

I teach iOS development on ZeroToAppStore.com.

Similar Posts