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.
- Evaluate if you need an optional value, and avoid them if possible.
- Do not make
Bool
s optional.- A tri-state
Bool
can be represented in a more structured way, such as anenum
with three well-namedcase
s.
- A tri-state
- Avoid making
Array
s 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.
URL
s created usinginit?(string:)
are a common example.
weak
properties must be optional by definition because they can becomenil
.
- 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
guard
statements and return early.