
Swift Functional Programming
By :

So far, we know that Optionals
wrap values in themselves. Wrapping means that the actual data is stored within an outer structure or container (See Higher-kinded types in the previous chapter).
For instance, we print optionalString
as follows:
print(optionalString)
The result will be Optional("A String literal")
.
How will we unwrap Optionals
and use the values that we need? There are different methods to unwrap Optionals
that we will go through in the following sections.
To unwrap Optionals
, the easiest and most dangerous method that we can use is force unwrapping. In short, !
can be used to force unwrap the value from Optional
.
The following example forcefully unwraps optionalString
:
optionalString = "An optional String" print(optionalString!)
Force unwrapping the Optionals
may cause errors if the optional does not have a value, so it is not recommended to use this approach as it is very hard to be sure if we are going to have values in Optionals
in different...