Challenge - 5 Problems
Swift Switch Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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))") }
Attempts:
2 left
💡 Hint
Check the conditions in the where clauses carefully.
✗ Incorrect
The point (3, 4) does not satisfy x == y or x == -y, so it matches the last case and prints the coordinates.
❓ Predict Output
intermediate2: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))") }
Attempts:
2 left
💡 Hint
Look at the tuple pattern matching order.
✗ Incorrect
The coordinate (0, 5) matches the first case where x is 0 and y is bound to 5.
🔧 Debug
advanced2: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") }
Attempts:
2 left
💡 Hint
Check the syntax of each case line carefully.
✗ Incorrect
The last case is missing a colon at the end of the case line, causing a syntax error.
❓ Predict Output
advanced2: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)") }
Attempts:
2 left
💡 Hint
Check the where clause condition in the first case.
✗ Incorrect
The result is a success with data 42, which is greater than 40, so the first case matches.
🧠 Conceptual
expert3: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" }
Attempts:
2 left
💡 Hint
Compare the values of x and y carefully.
✗ Incorrect
Since 2 is less than 3, the last case matches and message is set to "X is less".