Google News
logo
Swift - Interview Questions
What is the difference between Force Unwrapping Optionals and Implicitly Unwrapped Optionals?
Force unwrapping : It is the process of obtaining the value contained within an Optional. This action is risky since we are asking the compiler to extract the value and assign it to a new variable without seeing whether it is valid or not or nil.
let intNum: Int? = 1
// intSecNum have value 1.
let intSecNum: Int = intNum!
If we force unwrap an Optional item that contains nil, we get a fatalError, the application crashes, and there is no chance of recovering it.
let intNum: Int? = nil
let intSecNum= intNum! // force unwarp - fatal error
------------------------------
output :
fatal error: unexpectedly found nil while unwrapping an Optional value​

 

Implicitly unwrapped optionals : When we write an Implicitly unwrapped optional, we are defining a container that will do a force unwrap every time it is read.
var strGreet: String! = "Welcome"
/* it converts it into plain String as strGreet
automatically unwrapped it's content. */
let userName = strGreet

//assign nil
strGreet = nil
// it will throw fatal error
// fatal error: unexpectedly found nil while unwrapping an Optional value
let user2Name = strGreet​
Advertisement