Bird
Raised Fist0
Swiftprogramming~10 mins

Nil coalescing operator deep usage in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Nil coalescing operator deep usage
Evaluate optional value
↓
Is value nil?
No→Use unwrapped value
Yes↓
Use default fallback value
The nil coalescing operator checks if an optional has a value; if yes, it unwraps it, otherwise it uses a default value.
Execution Sample
Swift
let name: String? = nil
let displayName = name ?? "Guest"
print(displayName)
This code uses the nil coalescing operator to provide a default string when the optional 'name' is nil.
Execution Table
StepExpressionOptional ValueNil CheckResult
1let name: String? = nilnilN/Aname is nil
2name ?? "Guest"nilYesUse default "Guest"
3print(displayName)N/AN/AOutputs: Guest
💡 Execution stops after printing the fallback value because 'name' is nil.
Variable Tracker
VariableStartAfter Nil CoalescingFinal
namenilnilnil
displayNameN/A"Guest""Guest"
Key Moments - 3 Insights
Why does the operator return the default value instead of crashing when the optional is nil?
Because the nil coalescing operator safely unwraps the optional; if it's nil, it uses the default value instead, as shown in execution_table step 2.
What happens if the optional has a value instead of nil?
The operator unwraps and returns the actual value, skipping the default, as the nil check would be 'No' (not nil).
Can the default value be another expression or function call?
Yes, the default can be any expression or function call, evaluated only if the optional is nil.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'displayName' after step 2?
A"Guest"
Bnil
C"name"
DOptional("Guest")
💡 Hint
Check the 'Result' column in step 2 of the execution_table.
At which step does the nil coalescing operator decide to use the default value?
AStep 1
BStep 2
CStep 3
DNone
💡 Hint
Look at the 'Nil Check' and 'Result' columns in step 2.
If 'name' was "Alice" instead of nil, what would 'displayName' be after step 2?
A"Guest"
Bnil
C"Alice"
DOptional(nil)
💡 Hint
Recall that the operator unwraps the optional if not nil, as explained in key_moments 2.
Concept Snapshot
Nil coalescing operator (??) unwraps an optional if it has a value.
If the optional is nil, it returns a default fallback value.
Syntax: optionalValue ?? defaultValue
Useful for providing safe defaults without crashing.
Default value is only evaluated if needed.
Full Transcript
The nil coalescing operator in Swift checks if an optional variable has a value. If it does, it unwraps and uses that value. If the optional is nil, it uses a default value instead. For example, if 'name' is nil, 'name ?? "Guest"' returns "Guest". This prevents crashes from unwrapping nil optionals. The operator evaluates the default only when the optional is nil, making it efficient. This behavior is shown step-by-step in the execution table, where the optional 'name' is nil, so the default "Guest" is used and printed.

Practice

(1/5)
1. What does the nil coalescing operator ?? do in Swift?
easy
A. It returns the value of an optional if it is not nil, otherwise returns a default value.
B. It forces unwraps an optional and crashes if nil.
C. It converts a non-optional value into an optional.
D. It checks if two optionals are equal.

Solution

  1. Step 1: Understand the purpose of the nil coalescing operator

    The operator ?? is used to provide a default value when an optional is nil.
  2. Step 2: Compare with other options

    Options A, C, and D describe different behaviors unrelated to ??.
  3. Final Answer:

    It returns the value of an optional if it is not nil, otherwise returns a default value. -> Option A
  4. Quick Check:

    Nil coalescing operator = default value fallback [OK]
Hint: Remember: ?? means "use this if nil" [OK]
Common Mistakes:
  • Confusing ?? with forced unwrapping (!)
  • Thinking ?? converts types
  • Assuming ?? compares optionals
2. Which of the following is the correct syntax to use the nil coalescing operator in Swift?
easy
A. let value = optionalValue ??? defaultValue
B. let value = optionalValue ?: defaultValue
C. let value = optionalValue ? defaultValue
D. let value = optionalValue ?? defaultValue

Solution

  1. Step 1: Recall the correct syntax for nil coalescing

    The correct syntax uses two question marks: ?? between the optional and the default value.
  2. Step 2: Eliminate incorrect options

    Options B, C, and D use invalid or incorrect operators.
  3. Final Answer:

    let value = optionalValue ?? defaultValue -> Option D
  4. Quick Check:

    Syntax for nil coalescing = ?? [OK]
Hint: Look for exactly two question marks ?? [OK]
Common Mistakes:
  • Using ?: which is from other languages
  • Using single ? instead of ??
  • Adding extra question marks ???
3. What is the output of the following Swift code?
let a: Int? = nil
let b: Int? = 5
let c: Int? = nil
let result = a ?? b ?? c ?? 10
print(result)
medium
A. 5
B. 10
C. nil
D. Compilation error

Solution

  1. Step 1: Evaluate the chained nil coalescing

    The expression a ?? b ?? c ?? 10 checks each optional from left to right and returns the first non-nil value.
  2. Step 2: Check each optional's value

    a is nil, so move to b which is 5 (non-nil), so the result is 5.
  3. Final Answer:

    5 -> Option A
  4. Quick Check:

    First non-nil value = 5 [OK]
Hint: Chain ?? to pick first non-nil value [OK]
Common Mistakes:
  • Assuming nil is returned if first is nil
  • Ignoring chaining order
  • Thinking default 10 is always returned
4. Identify the error in this Swift code using nil coalescing:
let x: Int? = nil
let y: Int = 3
let z = x ?? y ?? 5
print(z)
medium
A. x must be non-optional
B. No error, code runs fine
C. y must be optional to use ??
D. Cannot use ?? with non-optional y

Solution

  1. Step 1: Understand the types involved in nil coalescing

    The operator ?? requires the right side to be the same type as the optional or a non-optional fallback value.
  2. Step 2: Analyze the expression x ?? y ?? 5

    Here, x is Int?, y is Int, but y ?? 5 is invalid because y is not optional, so you cannot use ?? on it.
  3. Final Answer:

    Cannot use ?? with non-optional y -> Cannot use ?? with non-optional y
  4. Quick Check:

    Right side of ?? must be optional or value [OK]
Hint: Right side of ?? must be optional or value, not non-optional with ?? [OK]
Common Mistakes:
  • Using ?? on non-optional values
  • Confusing optional and non-optional types
  • Assuming ?? works like || operator
5. Given the following Swift code, what will be the value of finalValue?
func getValue() -> Int? { return nil }
let a: Int? = nil
let b: Int? = getValue()
let c: Int? = 7
let finalValue = a ?? b ?? c ?? 0
hard
A. nil
B. 0
C. 7
D. Compilation error

Solution

  1. Step 1: Evaluate each optional in the chain

    a is nil, b is nil (from getValue()), c is 7 (non-nil).
  2. Step 2: Apply nil coalescing operator

    The expression a ?? b ?? c ?? 0 returns the first non-nil value, which is 7.
  3. Final Answer:

    7 -> Option C
  4. Quick Check:

    First non-nil in chain = 7 [OK]
Hint: Chain ?? to find first non-nil, else default [OK]
Common Mistakes:
  • Assuming function return nil means error
  • Ignoring that c is non-nil
  • Thinking default 0 is returned always
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard