Using optionals
The key to using optionals is to always verify that they contain a valid value prior to accessing them. The reason for this is if we attempt to use an optional value without verifying that it contains a valid value, we may encounter a runtime error, causing our application to crash. We use the term unwrapping to refer to the process of retrieving a value from an optional. We are going to introduce two methods for retrieving the values of an optional; please keep in mind that using optional binding is preferred.
Forced unwrapping of an optional
To unwrap or retrieve the value of an optional, we place an exclamation mark (!
) after the variable name. This is called forced unwrapping. Forced unwrapping, in this manner, is very dangerous and should be used only if we are certain that the variable contains a non-nil value. Otherwise, if it does contain a nil value, we will get a runtime error and the application will crash.
When we use the exclamation point to...