operator
?? {
associativity
right
precedence
}
Declarations
Performs a nil-coalescing operation, returning the wrapped value of an
Optional
instance or a default Optional
value.
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 defaultValue
is evaluated only if optional
is nil
. For example:
In this example, goodNumber
is assigned a value of 100
because
Int("100")
succeeds in returning a non-nil
result. When
notSoGoodNumber
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.
let
greeting
=
userPrefs
[
greetingKey
] ??
defaults
[
greetingKey
] ??
"Greetings!"
If userPrefs[greetingKey]
has a value, that value is assigned to
greeting
. If not, any value in defaults[greetingKey]
will succeed, and
if not that, greeting
will be set to the non-optional default value,
"Greetings!"
.
Parameters:
optional: An optional value.
defaultValue: A value to use as a default. defaultValue
and
optional
have the same type.
Declaration
func
??
<
T
>
(
optional
:
T
?,
defaultValue
: @
autoclosure
()
throws
-
>
T
?) -
>
T
?
Performs a nil-coalescing operation, returning the wrapped value of an
Optional
instance or a default value.A nil-coalescing operation unwraps the left-hand side if it has a value, or it returns the right-hand side as a default. The result of this operation will have the nonoptional type of the left-hand side's
Wrapped
type.This operator uses short-circuit evaluation:
optional
is checked first, anddefaultValue
is evaluated only ifoptional
isnil
. For example:In this example,
goodNumber
is assigned a value of100
becauseInt("100")
succeeded in returning a non-nil
result. WhennotSoGoodNumber
is initialized,Int("invalid-input")
fails and returnsnil
, and so thegetDefault()
method is called to supply a default value.Parameters: optional: An optional value. defaultValue: A value to use as a default.
defaultValue
is the same type as theWrapped
type ofoptional
.Declaration
func
??
<
T
>
(
optional
:
T
?,
defaultValue
: @
autoclosure
()
throws
-
>
T
) -
>
T