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 city: String? = nil
if let name = city {
    print("City: \(name)")
} else {
    print("No city provided")
}
ANo city provided
BCity:
CCity: nil
DError: Optional not unwrapped
Step-by-Step Solution
Solution:
  1. Step 1: Check the optional value

    The variable city is nil, so the optional is empty.
  2. Step 2: Optional binding with if let

    The if let fails to unwrap, so the else block runs.
  3. Final Answer:

    No city provided -> Option A
  4. Quick Check:

    Nil optional triggers else block [OK]
Quick Trick: Nil optional skips if let block, runs else [OK]
Common Mistakes:
  • Expecting if block to run with nil
  • Printing 'City: nil' instead of else message
  • Confusing nil with empty string

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes