Bird
0
0

What will be printed by this Swift code?

medium📝 Predict Output Q5 of 15
Swift - Operators and Expressions
What will be printed by this Swift code?
let x: String? = nil
let y: String? = "Hello"
let z = x ?? (y ?? "Default")
print(z)
A"Hello"
B"Default"
Cnil
DOptional("Hello")
Step-by-Step Solution
Solution:
  1. Step 1: Evaluate first nil coalescing

    x is nil, so x ?? (y ?? "Default") evaluates to y ?? "Default".
  2. Step 2: Evaluate second nil coalescing

    Since y is not nil, y ?? "Default" unwraps y to "Hello".
  3. Final Answer:

    "Hello" -> Option A
  4. Quick Check:

    Chained ?? unwraps first non-nil string = C [OK]
Quick Trick: ?? unwraps optionals in order until non-nil found [OK]
Common Mistakes:
  • Expecting Optional("Hello") instead of unwrapped
  • Assuming nil is printed
  • Confusing default fallback usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes