In general, in programming we want to avoid variables that have no value (null
or nil
) because using them often results in undefined behaviour (exceptions, errors, crashes).
For example, it is a common practice for Array
references to be set to empty arrays instead of nil
. On an empty array we can use all the Array
methods, e.g. indexOf
or count
. Using them on nil
would result in a crash.
Optionals allow us to specify that some variables are never empty, therefore we can use them safely and the compiler checks that nil
is never assigned to them. Also, the compiler enforces that every conversion from optionals to non-optionals is explicit (we are always checking for nil
when needed).
So the answer would be that optionals:
- Enforce good programming practices.
- Allow for better code checking at compilation time
Thus preventing programming errors.
Also note that the you should always try to avoid optionals when possible. The greatest power of optionals is the fact that most variables are not optionals.