Fatal error: unexpectedly found nil while unwrapping an Optional value

fatal error: unexpectedly found nil while unwrapping an Optional value

This error is caused by unconditionally unwrapping an optional  which had nil.

Optional is a type in swift which can either contain a value or no value nil.

When a optional variable or constant which contains nil is forced unwrapped with ! , It generates a runtime error.

We can safely deal with Optionals using if let,  guard let, nil coalescing.

Copy paste the following code in playground

//: Playground - noun: a place where people can play

// if let
let a:Int? = nil
if let b = a {
    print ("\(b)")
}
else{
    print("a was nil but the assignment didnt cause runtime error")
}


// Nil-Coalescing
let b = a ?? 3  // Nil-Coalescing replaces nil with default value and unlike ternary operator it works for false as well
print ("\(b)")


//guard let
func testGuard()
{
guard let b = a else{
    print("a was nil but the assignment didnt cause runtime error")
    return
}
}
testGuard()


//forced unwrapping error

let c = a!

 

A pat on the back !!

Leave a Reply

Your email address will not be published. Required fields are marked *