Challenge - 5 Problems
Switch Statement Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Switch with tuple pattern matching
What is the output of this Swift code using a switch statement with tuple pattern matching?
Swift
let point = (2, -2) switch point { case (let x, let y) where x == y: print("On the line x == y") case (let x, let y) where x == -y: print("On the line x == -y") default: print("Just a point") }
Attempts:
2 left
💡 Hint
Check the conditions in the where clauses carefully.
✗ Incorrect
The tuple (2, -2) matches the second case because 2 == -(-2) is true, so it prints "On the line x == -y".
❓ Predict Output
intermediate2:00remaining
Switch with value binding and fallthrough
What will be printed when this Swift code runs?
Swift
let number = 3 switch number { case 1: print("One") case 2, 3: print("Two or Three") fallthrough case 4: print("Four") default: print("Other") }
Attempts:
2 left
💡 Hint
Remember what fallthrough does in Swift switch statements.
✗ Incorrect
The case 3 matches and prints "Two or Three", then fallthrough causes the next case (4) to execute, printing "Four".
🔧 Debug
advanced2:00remaining
Why does this switch cause a compile error?
This Swift code causes a compile error. What is the reason?
Swift
let value = 5 switch value { case 1..<5: print("Less than 5") case 5: print("Equal to 5") case 6...10: print("Between 6 and 10") default: print("Other") }
Attempts:
2 left
💡 Hint
Check the syntax for the default case in Swift switch statements.
✗ Incorrect
Swift requires the default case to be written as 'default:', not 'case _:'. Using 'case _:' causes a syntax error.
❓ Predict Output
advanced2:00remaining
Switch with multiple patterns and where clause
What is the output of this Swift code?
Swift
let char: Character = "e" switch char { case "a", "e", "i", "o", "u" where char.isLowercase: print("Lowercase vowel") case "A", "E", "I", "O", "U": print("Uppercase vowel") default: print("Consonant") }
Attempts:
2 left
💡 Hint
Check the placement of the where clause with multiple patterns.
✗ Incorrect
In Swift, a where clause cannot be applied to multiple patterns combined with commas. This causes a compile error.
❓ Predict Output
expert3:00remaining
Switch with enum and associated values
Given this Swift enum and switch, what will be printed?
Swift
enum Result { case success(Int) case failure(String) } let result = Result.success(42) switch result { case .success(let code) where code > 40: print("Success with code > 40") case .success: print("Success with code <= 40") case .failure(let message): print("Failure: \(message)") }
Attempts:
2 left
💡 Hint
Look at the associated value and the where clause condition.
✗ Incorrect
The enum case is success with associated value 42, which is greater than 40, so the first case matches and prints "Success with code > 40".