Optional Operators
Nil-coalescing operator (??
)
The nil-coalescing operator ??
returns the value inside an optional if it contains a value, or returns an alternative value if the optional has no value (i.e., the optional value is nil
).
If the left-hand side is non-nil, the right-hand side is not evaluated:
_10// Declare a constant which has an optional integer type_10//_10let a: Int? = nil_10_10// Declare a constant with a non-optional integer type,_10// which is initialized to `a` if it is non-nil, or 42 otherwise._10//_10let b: Int = a ?? 42_10// `b` is 42, as `a` is nil
The nil-coalescing operator can only be applied to values that have an optional type:
_10// Declare a constant with a non-optional integer type._10//_10let a = 1_10_10// Invalid: nil-coalescing operator is applied to a value which has a non-optional type_10// (a has the non-optional type `Int`)._10//_10let b = a ?? 2
_10// Invalid: nil-coalescing operator is applied to a value which has a non-optional type_10// (the integer literal is of type `Int`)._10//_10let c = 1 ?? 2
The type of the right-hand side of the operator (the alternative value) must be a subtype of the type of left-hand side. This means that the right-hand side of the operator must be the non-optional or optional type matching the type of the left-hand side:
_11// Declare a constant with an optional integer type._11//_11let a: Int? = nil_11let b: Int? = 1_11let c = a ?? b_11// `c` is `1` and has type `Int?`_11_11// Invalid: nil-coalescing operator is applied to a value of type `Int?`,_11// but the alternative has type `Bool`._11//_11let d = a ?? false
Force unwrap operator (!
)
The force-unwrap operator (!
) returns the value inside an optional if it contains a value, or panics and aborts the execution if the optional has no value (i.e., the optional value is nil
):
_19// Declare a constant which has an optional integer type_19//_19let a: Int? = nil_19_19// Declare a constant with a non-optional integer type,_19// which is initialized to `a` if `a` is non-nil._19// If `a` is nil, the program aborts._19//_19let b: Int = a!_19// The program aborts because `a` is nil._19_19// Declare another optional integer constant_19let c: Int? = 3_19_19// Declare a non-optional integer_19// which is initialized to `c` if `c` is non-nil._19// If `c` is nil, the program aborts._19let d: Int = c!_19// `d` is initialized to 3 because c isn't nil.
The force-unwrap operator can only be applied to values that have an optional type:
_10// Declare a constant with a non-optional integer type._10//_10let a = 1_10_10// Invalid: force-unwrap operator is applied to a value which has a_10// non-optional type (`a` has the non-optional type `Int`)._10//_10let b = a!
_10// Invalid: The force-unwrap operator is applied_10// to a value which has a non-optional type_10// (the integer literal is of type `Int`)._10//_10let c = 1!