Fatal error: Unexpectedly found nil while unwrapping an Optional value

In this tutorial, we will learn how to solve Swift Fatal error: Unexpectedly found nil while unwrapping an Optional value.

To solve this fatal error, we have to make sure that the optional variable is not nil. We can either conditionally check if the value in this optional variable is nil, or make sure to assign a value before using the optional variable.

Let us recreate this Fatal error, and then work on the ways to solve it.

Consider the following program, where we declare an optional variable x and not initialize it with any value. So, x is nil. Now, when we try to use this optional variable x in an expression, Swift would cause a runtime error as shown in the following.

main.swift

</>
Copy
var x : Int?
let result = x! + 10
print(result)

Output

[Solved] Swift Fatal error: Unexpectedly found nil while unwrapping an Optional value

Now, to solve this issue, let us check if x is not nil, and only if x is not nil, we shall use x.

main.swift

</>
Copy
var x : Int?
if x != nil {
    let result = x! + 10
    print(result)
} else {
    print("x is nil. Please check.")
}

Or, if we can make sure that the optional variable is initialized with a value, before using it, we could solve this runtime error.

main.swift

</>
Copy
var x : Int? = 14
let result = x! + 10
print(result)

Conclusion

In this Swift Tutorial, we learned how to solve Swift Fatal error: Unexpectedly found nil while unwrapping an Optional value.