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 optional binding with if let
What is the output of this Swift code snippet?
Swift
var optionalName: String? = "Alice" if let name = optionalName { print("Hello, \(name)!") } else { print("No name found.") }
Attempts:
2 left
💡 Hint
Remember that if let unwraps the optional safely.
✗ Incorrect
The if let statement unwraps the optional 'optionalName' safely. Since it contains "Alice", the code inside the if block runs, printing "Hello, Alice!".
❓ Predict Output
intermediate2:00remaining
Optional binding with nil value
What will be printed when this Swift code runs?
Swift
var optionalNumber: Int? = nil if let number = optionalNumber { print("Number is \(number)") } else { print("No number available") }
Attempts:
2 left
💡 Hint
Check what happens when the optional is nil.
✗ Incorrect
Since 'optionalNumber' is nil, the if let binding fails and the else block runs, printing "No number available".
🔧 Debug
advanced2:00remaining
Identify the error in optional binding
What error does this Swift code produce?
Swift
var optionalString: String? = "Hello" if let optionalString = optionalString { print(optionalString) }
Attempts:
2 left
💡 Hint
Check if shadowing the variable name is allowed in Swift.
✗ Incorrect
Shadowing the variable name in if let is allowed in Swift. The code unwraps the optional and prints "Hello" without error.
📝 Syntax
advanced2:00remaining
Syntax error in optional binding
Which option contains the correct syntax for optional binding with if let?
Attempts:
2 left
💡 Hint
Remember the correct syntax uses '=' to assign the unwrapped value.
✗ Incorrect
Option B uses the correct syntax: 'if let name = optionalName { ... }'. Other options have syntax errors like missing '=' or braces.
🚀 Application
expert3:00remaining
Count non-nil values using optional binding
Given the array of optional integers, what is the value of 'count' after this code runs?
Swift
let numbers: [Int?] = [1, nil, 3, nil, 5] var count = 0 for case let number? in numbers { count += 1 }
Attempts:
2 left
💡 Hint
The 'for case let number?' syntax unwraps non-nil optionals in the array.
✗ Incorrect
The loop counts only non-nil values: 1, 3, and 5. So count is 3.