0
0
Swiftprogramming~20 mins

Optional binding with if let in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Optional Binding Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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.")
}
AHello, Alice!
BNo name found.
COptional("Alice")
DHello, Optional("Alice")!
Attempts:
2 left
💡 Hint
Remember that if let unwraps the optional safely.
Predict Output
intermediate
2: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")
}
ANo number available
BNumber is 0
Cnil
DNumber is nil
Attempts:
2 left
💡 Hint
Check what happens when the optional is nil.
🔧 Debug
advanced
2: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)
}
AError: Cannot shadow variable 'optionalString' in if let
BError: Variable 'optionalString' used before being initialized
CNo error, prints Hello
DError: Missing else block for if let
Attempts:
2 left
💡 Hint
Check if shadowing the variable name is allowed in Swift.
📝 Syntax
advanced
2:00remaining
Syntax error in optional binding
Which option contains the correct syntax for optional binding with if let?
A
if let name optionalName {
    print(name)
}
B
if let name = optionalName {
    print(name)
}
C
if let name = optionalName
    print(name)
D
if let name == optionalName {
    print(name)
}
Attempts:
2 left
💡 Hint
Remember the correct syntax uses '=' to assign the unwrapped value.
🚀 Application
expert
3: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
}
A2
B5
C0
D3
Attempts:
2 left
💡 Hint
The 'for case let number?' syntax unwraps non-nil optionals in the array.