Challenge - 5 Problems
Swift Optional Binding Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of multiple optional binding with commas
What is the output of this Swift code snippet?
Swift
let a: Int? = 5 let b: Int? = 10 if let x = a, let y = b { print(x + y) } else { print("No value") }
Attempts:
2 left
💡 Hint
Both a and b have values, so both bindings succeed.
✗ Incorrect
Both optionals a and b contain values, so the if let statement unwraps both successfully and prints their sum.
❓ Predict Output
intermediate2:00remaining
Output when one optional is nil in multiple binding
What will this Swift code print?
Swift
let a: Int? = nil let b: Int? = 3 if let x = a, let y = b { print(x * y) } else { print("Missing value") }
Attempts:
2 left
💡 Hint
If any optional is nil, the whole if let fails.
✗ Incorrect
Since a is nil, the first binding fails and the else branch runs, printing "Missing value".
🔧 Debug
advanced2:00remaining
Identify the error in multiple optional binding
What error does this Swift code produce?
Swift
let a: Int? = 2 let b: Int? = 3 if let x = a; let y = b { print(x + y) }
Attempts:
2 left
💡 Hint
Check the syntax for multiple optional bindings in if statements.
✗ Incorrect
Swift requires commas to separate multiple optional bindings in if statements, not semicolons.
❓ Predict Output
advanced2:00remaining
Output of nested optional binding
What is printed by this Swift code?
Swift
let a: Int? = 4 let b: Int? = nil if let x = a { if let y = b { print(x * y) } else { print("b is nil") } } else { print("a is nil") }
Attempts:
2 left
💡 Hint
Check which optional is nil and which is not.
✗ Incorrect
a is not nil, so the outer if succeeds. b is nil, so the inner else branch prints "b is nil".
🧠 Conceptual
expert2:00remaining
Behavior of multiple optional binding with where clause
Consider this Swift code. What is the output?
Swift
let a: Int? = 7 let b: Int? = 3 if let x = a, let y = b, x > y { print("x is greater") } else { print("Condition not met") }
Attempts:
2 left
💡 Hint
All bindings and conditions must be true for the if to run.
✗ Incorrect
Both optionals have values and the condition x > y is true, so it prints "x is greater".