0
0
Swiftprogramming~20 mins

Multiple optional binding 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 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")
}
A15
BNo value
CCompilation error
DRuntime error
Attempts:
2 left
💡 Hint
Both a and b have values, so both bindings succeed.
Predict Output
intermediate
2: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")
}
ARuntime error
BMissing value
CCompilation error
D0
Attempts:
2 left
💡 Hint
If any optional is nil, the whole if let fails.
🔧 Debug
advanced
2: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)
}
ASyntax error: unexpected ';' in if statement
BRuntime error: nil unwrapping
CNo error, prints 5
DType error: cannot assign optional to non-optional
Attempts:
2 left
💡 Hint
Check the syntax for multiple optional bindings in if statements.
Predict Output
advanced
2: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")
}
A16
Ba is nil
Cb is nil
DRuntime error
Attempts:
2 left
💡 Hint
Check which optional is nil and which is not.
🧠 Conceptual
expert
2: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")
}
ACondition not met
BRuntime error
CCompilation error
Dx is greater
Attempts:
2 left
💡 Hint
All bindings and conditions must be true for the if to run.