Swift Tutorial Swift Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

Swift - Nil coalescing operator



The Swift nil-coalescing operator (a ?? b) returns right-hand side operand when left-hand side operand is nil, otherwise returns left-hand side operand. The expression a is always of an optional type. The expression b must match the type that is stored in a.

Please note that If the value of a is non-nil, the value of b is not evaluated. This is known as short-circuit evaluation.

Example:

The example below shows how to use nil-coalescing operator to choose between a default color and an optional user-defined color.

//defaults to nil
var AppColor: String?

var DefaultColor = "Blue"

print("Color of App = \(AppColor ?? DefaultColor)")

The output of the above code will be:

Color of App = Blue

❮ Swift - Operators

5