Bird
0
0

What will be the output of the following Swift code?

medium📝 Predict Output Q13 of 15
Swift - Optionals
What will be the output of the following Swift code?
var name: String? = "Alice"
if let unwrappedName = name {
    print("Hello, \(unwrappedName)!")
} else {
    print("No name provided.")
}
ANo name provided.
BHello, Alice!
COptional("Alice")
DError: Cannot unwrap optional
Step-by-Step Solution
Solution:
  1. Step 1: Understand optional binding with if let

    The code uses 'if let' to safely unwrap the optional 'name'. Since 'name' contains "Alice", unwrapping succeeds.
  2. Step 2: Determine which print statement runs

    Because unwrapping succeeds, the first print statement runs, printing "Hello, Alice!".
  3. Final Answer:

    Hello, Alice! -> Option B
  4. Quick Check:

    Optional binding unwraps value = prints greeting [OK]
Quick Trick: if let unwraps optionals safely [OK]
Common Mistakes:
  • Expecting 'Optional("Alice")' to print
  • Thinking else block runs when value exists
  • Confusing optional binding with forced unwrap

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes