It will take about 1 minutes to finish reading this article.
1. Force unwrapping
Forced unwrapping of optional types means that when we are sure that an optional type must have a value, we can use the exclamation mark ! to force parsing of it and thus get the value in it. If we use forced parsing on an optional type that has no value, a runtime error will be triggered. Therefore, when using forced parsing, we must make sure that the optional type does have a value.
1 | let possibleString: String? = "An optional string." |
2. Implicitly Unwrapped Optionals
An implicitly Unwrapped Optionals type is a special kind of optional type that is declared with the exclamation mark ! flag to indicate that this optional type can be implicitly treated as a non-optional type for subsequent use, without the need to force resolution each time. At declaration time, we can declare an optional type as an implicitly resolved optional type, which will throw an error at runtime if the variable or constant is not initialized to a non-nil value at the time of use.
1 | let assumedString2: String! = "123" |
1 | let assumedString1: String! = nil |
So, implicitly unwrapped optionals type is special optionals type that can be used to get the value in it directly using the variable name, without having to force unwrapping every time.
We can do these as follows:
1 | if assumedString != nil { |
You can also use an implicitly unwrapped optional with optional binding, to check and unwrap its value in a single statement:
1 | if let definiteString = assumedString { |