So your code is crashing with EXC_BAD_INSTRUCTION
and you are getting a error like
Fatal error: Unexpectedly found nil while unwrapping an Optional value
or
Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
This crash arises when we attempt to forcefully or Implicitly unwrap an optional and that optional, as the name suggests, does not contain any value.
In swift optional are variables which can have a value or no value at all. and when we try to extract value from it as shown below
//Forced unwrapping var optionalValue: Int? var anotherValue = optionalValue! + 2 //Implicit unwrapping var optionalValue: Int! // Note the exclamation mark var anotherValue = optionalValue + 2
In case of forced unwrapping of optional value we can mitigate the error by using any of the following three approach
If Statements and Forced Unwrapping
We can use if statement to check that the optional is not nil and then force unwrap it as shown below
if optionalVar != nil{ print(optionalVar!) //force unwrap safely under if }
Optional Binding
In optional binding, we assign the optional to a temporary constant or variable in a if let
statement.
if let constantName = someOptional { statements } if let tempConstant = someOptional{ print(tempConstant) //Note no need to use ! mark }
Using Guard
We can also use guard which has a specific advantage over if let
. Option binding using a guard
makes the variable available below the guard
statement is the same scope as the guard statement itself. In case of if let statement the temporary variable or constant is available only inside the if let
block. See example below
//Guard example guard let tempConst = someOptional else{ return // or throw } //tempConst is available here onwards in the same scope as that of guard. let a = tempConst + 2;
Nil-Coalescing
// Nil-Coalescing let b = a ?? 3 // Nil-Coalescing replaces nil with a default value and unlike ternary operator, it works for false as well print ("(b)")
Any of the above approaches can be taken to safely use optional inside your code. Implicit unwrapping should only be used when you are absolutely sure that a value should be present once it has been assigned and if it is not present then the state of the app is compromised and a crash should occur e.g user token
Hope its clear now how to use optionals safely