Optionals
May 29, 2019 ยท View on GitHub
When do we use them?
Optionals are used when something is not known at the time of initialization, when an API can fail, or when the absence of a value provides additional meaning.
Key Considerations
- Evaluate if you need an optional value, and avoid them if possible.
- Do not make
Bools optional.- A tri-state
Boolcan be represented in a more structured way, such as anenumwith three well-namedcases.
- A tri-state
- Avoid making
Arrays optional.- Only do this if it provides meaning beyond it just being empty.
- System APIs may require us to use optional values since they return optional values.
URLs created usinginit?(string:)are a common example.
weakproperties must be optional by definition because they can becomenil.
Dealing with Optionals
- Always handle unwrapping optionals safely.
- We prefer conditional binding (
if let) overflatMap. - If a function requires an optional value to have a value, we opt to bind with
guardstatements and return early.