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?

let x: Int? = 5
let y: Int? = nil

if let a = x, let b = y {
    print(a + b)
} else {
    print("Failed to unwrap")
}
AFailed to unwrap
BRuntime error
C10
D0
Step-by-Step Solution
Solution:
  1. Step 1: Check values of optionals

    Variable x has value 5, but y is nil.
  2. Step 2: Evaluate multiple optional binding condition

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

    Failed to unwrap -> Option A
  4. Quick Check:

    Any nil optional skips the if block [OK]
Quick Trick: If any optional is nil, else block runs [OK]
Common Mistakes:
  • Assuming nil optionals get default values
  • Expecting sum even if one optional is nil
  • Confusing optional binding with forced unwrapping

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes