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 where clause filtering
What is the output of this Swift code using a switch with a where clause?
Swift
let number = 15 switch number { case let x where x % 3 == 0 && x % 5 == 0: print("FizzBuzz") case let x where x % 3 == 0: print("Fizz") case let x where x % 5 == 0: print("Buzz") default: print(number) }
Attempts:
2 left
💡 Hint
Remember the order of cases and how where clauses filter values.
✗ Incorrect
The number 15 is divisible by both 3 and 5, so the first case with where clause matching both conditions runs, printing "FizzBuzz".
❓ Predict Output
intermediate2:00remaining
Switch with multiple where clauses
What will this Swift code print?
Swift
let point = (x: 3, y: 4) switch point { case let (x, y) where x == y: print("On the diagonal") case let (x, y) where x > y: print("Above the diagonal") case let (x, y) where x < y: print("Below the diagonal") default: print("Unknown") }
Attempts:
2 left
💡 Hint
Compare x and y values carefully.
✗ Incorrect
Since x=3 and y=4, x < y is true, so it prints "Below the diagonal".
🔧 Debug
advanced2:00remaining
Identify the error in switch with where clause
This Swift code does not compile. What is the error?
Swift
let value = 10 switch value { case let x where x > 5: print("Greater than 5") case let x where x <= 5: print("5 or less") }
Attempts:
2 left
💡 Hint
Check punctuation after case statements.
✗ Incorrect
The first case is missing a colon ':' after the where clause, causing a syntax error.
🚀 Application
advanced2:00remaining
Using switch with where to classify ages
Given this Swift code, what is the output?
Swift
let age = 20 switch age { case let x where x >= 0 && x <= 12: print("Child") case let x where x >= 13 && x <= 19: print("Teenager") case let x where x >= 20 && x <= 64: print("Adult") case let x where x >= 65: print("Senior") default: print("Invalid age") }
Attempts:
2 left
💡 Hint
Check which age range 20 falls into.
✗ Incorrect
Age 20 fits the third case where age is between 20 and 64, so it prints "Adult".
🧠 Conceptual
expert3:00remaining
Behavior of switch with overlapping where clauses
Consider this Swift code snippet. Which case will execute and why?
Swift
let number = 8 switch number { case let x where x > 5: print("Greater than 5") case let x where x > 3: print("Greater than 3") default: print("3 or less") }
Attempts:
2 left
💡 Hint
Switch executes the first matching case only.
✗ Incorrect
The switch stops at the first case where x > 5 is true (8 > 5), so it prints "Greater than 5" and does not check further cases.