Bird
0
0

What will be printed by this Swift code?

medium📝 Predict Output Q5 of 15
Swift - Optionals

What will be printed by this Swift code?

let first: String? = "Hello"
let second: String? = nil
if let a = first, let b = second {
    print(a + b)
} else {
    print("Missing value")
}
AMissing value
BHello
CHellonil
DCompile error
Step-by-Step Solution
Solution:
  1. Step 1: Check optional values

    first is "Hello", second is nil.
  2. Step 2: Multiple optional binding fails

    Since second is nil, the if condition fails and else block runs.
  3. Final Answer:

    Missing value -> Option A
  4. Quick Check:

    Nil optional causes else block [OK]
Quick Trick: If any optional is nil, else runs [OK]
Common Mistakes:
  • Assuming nil converts to empty string
  • Expecting partial unwrapping
  • Thinking code crashes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes