08. Force unwrapping and Implicitly Unwrapped Optionals

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
2
let possibleString: String? = "An optional string."
let forcedString: String = possibleString! // Need exclamation mark to get value

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
2
3
let assumedString2: String! = "123"
let possibleString2: String? = assumedString2
let implicitString2: String = assumedString2 //No exclamation point needed
1
2
3
let assumedString1: String! = nil
let possibleString1: String? = assumedString1
let implicitString1: String = assumedString1 // Report Error

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
2
3
4
if assumedString != nil {
print(assumedString!)
}
// Prints "An implicitly unwrapped optional string."

You can also use an implicitly unwrapped optional with optional binding, to check and unwrap its value in a single statement:

1
2
3
4
if let definiteString = assumedString {
print(definiteString)
}
// Prints "An implicitly unwrapped optional string."