Performs a nil-coalescing operation, returning the wrapped value of an
Optional instance or a default
- Xcode 8.0+
- Swift Standard Library
An optional value.
A value to use as a default.
optionalhave the same type.
A nil-coalescing operation unwraps the left-hand side if it has a value, or returns the right-hand side as a default. The result of this operation will be the same type as its arguments.
This operator uses short-circuit evaluation:
optional is checked first, and
default is evaluated only if
nil. For example:
In this example,
good is assigned a value of
Int("100") succeeds in returning a non-
nil result. When
not is initialized,
Int("invalid-input") fails and returns
nil, and so
Int("42") is called to supply a default value.
Because the result of this nil-coalescing operation is itself an optional value, you can chain default values by using
?? multiple times. The first optional value that isn’t
nil stops the chain and becomes the result of the whole expression. The next example tries to find the correct text for a greeting in two separate dictionaries before falling back to a static default.
user has a value, that value is assigned to
greeting. If not, any value in
defaults[greeting will succeed, and if not that,
greeting will be set to the non-optional default value,