I was very confused about the forced and implicitly unwrapping in the beginning. Now the following understandings come from my self-study
There is no such an action named implicitly unwrapping but the implicitly unwrapped Optionals. implicitly unwrapped Optionals and the normal Optionals are both Optionals, the different is, when access an implicitly unwrapped Optional you confidently know that there is a valid value under the hood and ready for use. The normal Optionals need if-let binding or forced unwrapping action to access the possible values behinds the optional variables.
Forced unwrapping is an action acts on the normal Optionals ;
Implicitly unwrapped Optionals are Optionlas, usually used for class initialization and will pass values without exclamation mark when using.
Am I right? If my understanding is not precisely , I would appreciate that you could correct me.
An Optional value is a container of some type (
UIColor, ...), it could contain the value (
.greenColor(), ...) or
let anOptionalInt: Int? = 1 let anotherOptionalInt: Int? = nil
When in Swift we see an Optional value we think: ok this could contain the actual value or
It's the action of extracting the value contained inside an
This operation is dangerous because you are telling the compiler: I am sure this Optional value does contain a real value, extract it!
let anOptionalInt: Int? = 1 let anInt: Int = anOptionalInt!
anInt contains the value 1.
If we perform a force unwrapping on an Optional value that happens to contain nil we get a fatalError, the app does crash and there no way to recover it.
let anotherOptionalInt: Int? = nil let anotherInt = anotherOptionalInt! fatal error: unexpectedly found nil while unwrapping an Optional value
When we define an Implicitly unwrapped optional, we define a container that will automatically perform a force unwrap each time we read it.
var text: String! = "Hello"
If now we read
let name = text
we don't get an Optional
String but a plain
text automatically unwrapped it's content.
However text is still an optional so we can put a
nil value inside it
text = nil
But as soon as we read it (and it contains
nil) we get a fatal error because we are unwrapping an optional containing
let anotherName = text fatal error: unexpectedly found nil while unwrapping an Optional value