0
0
Swiftprogramming~10 mins

Nil coalescing operator (??) in Swift - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Nil coalescing operator (??)
Optional value
Is it nil?
Yes
Use default value
The nil coalescing operator checks if an optional has a value; if yes, it uses that value, otherwise it uses a default.
Execution Sample
Swift
let name: String? = nil
let displayName = name ?? "Guest"
print(displayName)
This code uses ?? to provide "Guest" if name is nil, then prints the result.
Execution Table
StepVariableValueConditionActionOutput
1namenilname == nilUse default "Guest""Guest"
2displayName"Guest"-Assign displayName = "Guest"-
3---Print displayNameGuest
💡 Execution ends after printing displayName.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
namenilnilnilnil
displayNameundefinedundefined"Guest""Guest"
Key Moments - 2 Insights
Why does displayName get "Guest" instead of nil?
Because name is nil (see execution_table step 1), the ?? operator uses the default "Guest" value.
What if name had a value instead of nil?
Then the ?? operator would use that value directly, skipping the default (not shown here but implied).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table step 1, what is the value of 'name'?
Anil
B"Guest"
Cundefined
D"name"
💡 Hint
Check the 'Value' column for 'name' at step 1 in execution_table.
At which step is displayName assigned a value?
AStep 1
BStep 3
CStep 2
DNever assigned
💡 Hint
Look at the 'Action' column in execution_table for displayName assignment.
If name was "Alice" instead of nil, what would displayName be after step 2?
Anil
B"Alice"
C"Guest"
Dundefined
💡 Hint
Recall how ?? uses the optional value if not nil, see concept_flow.
Concept Snapshot
Syntax: optionalValue ?? defaultValue

Behavior: Returns optionalValue if not nil; otherwise returns defaultValue.

Use to provide fallback values for optionals.

Example: let x = name ?? "Guest"

Simple and safe way to handle nil optionals.
Full Transcript
The nil coalescing operator (??) in Swift checks if an optional value is nil. If the optional has a value, it uses that value. If it is nil, it uses a default value provided after the operator. For example, if name is nil, name ?? "Guest" results in "Guest". This operator helps avoid writing longer if-else code to unwrap optionals safely. In the example code, name is nil, so displayName becomes "Guest" and that is printed. If name had a value like "Alice", displayName would be "Alice" instead. This operator is a simple way to provide fallback values for optionals.