0
0
Swiftprogramming~20 mins

Switch with value binding in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Switch Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of switch with value binding and where clause
What is the output of this Swift code?
Swift
let point = (3, 4)
switch point {
case let (x, y) where x == y:
    print("On the line x == y")
case let (x, y) where x == -y:
    print("On the line x == -y")
case let (x, y):
    print("Somewhere else at (\(x), \(y))")
}
AOn the line x == y
BOn the line x == -y
CSomewhere else at (3, 4)
DNo output
Attempts:
2 left
💡 Hint
Check the conditions in the where clauses carefully.
Predict Output
intermediate
2:00remaining
Switch with value binding and tuple pattern
What will this Swift code print?
Swift
let coordinate = (0, 5)
switch coordinate {
case (0, let y):
    print("On the y-axis at \(y)")
case (let x, 0):
    print("On the x-axis at \(x)")
case let (x, y):
    print("Somewhere else at (\(x), \(y))")
}
AOn the x-axis at 0
BOn the y-axis at 5
CSomewhere else at (0, 5)
DNo output
Attempts:
2 left
💡 Hint
Look at the tuple pattern matching order.
🔧 Debug
advanced
2:00remaining
Identify the error in switch with value binding
What error does this Swift code produce?
Swift
let number = 10
switch number {
case let x where x > 5:
    print("Greater than 5")
case let x where x < 5:
    print("Less than 5")
case let x where x == 5:
    print("Equal to 5")
}
ANo error, prints 'Greater than 5'
BRuntimeError: No matching case found
CSyntaxError: Missing parentheses in where clause
DSyntaxError: Missing colon after case condition
Attempts:
2 left
💡 Hint
Check the syntax of each case line carefully.
Predict Output
advanced
2:00remaining
Switch with nested value binding and pattern matching
What is the output of this Swift code?
Swift
enum Result {
    case success(data: Int)
    case failure(error: String)
}

let result = Result.success(data: 42)
switch result {
case .success(let data) where data > 40:
    print("Big success with \(data)")
case .success(let data):
    print("Success with \(data)")
case .failure(let error):
    print("Failed with error: \(error)")
}
ABig success with 42
BSuccess with 42
CFailed with error: 42
DNo output
Attempts:
2 left
💡 Hint
Check the where clause condition in the first case.
🧠 Conceptual
expert
3:00remaining
Value binding behavior in switch cases
Consider this Swift code snippet. What will be the value of variable 'message' after execution?
Swift
let value = (2, 3)
var message = ""
switch value {
case let (x, y) where x == y:
    message = "Equal"
case let (x, y) where x > y:
    message = "X is greater"
case let (x, y):
    message = "X is less"
}
A"X is less"
B"X is greater"
C"Equal"
D"No match"
Attempts:
2 left
💡 Hint
Compare the values of x and y carefully.