Bird
0
0

What will be the output of this Swift code?

medium📝 Predict Output Q5 of 15
Swift - Optionals
What will be the output of this Swift code?
var text: String? = nil
print(text ?? "Default")
Anil
BDefault
COptional(nil)
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Understand nil coalescing operator

    The operator ?? returns the left value if not nil, else the right value.
  2. Step 2: Apply to given code

    Since text is nil, the expression returns "Default" which is printed.
  3. Final Answer:

    Default -> Option B
  4. Quick Check:

    Nil coalescing returns default = B [OK]
Quick Trick: Use ?? to provide a default for nil optionals [OK]
Common Mistakes:
  • Expecting nil to print as string
  • Confusing Optional(nil) with nil
  • Thinking it causes runtime error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes