0
0
Swiftprogramming~20 mins

Switch with where clauses 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 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)
}
AFizz
BFizzBuzz
CBuzz
D15
Attempts:
2 left
💡 Hint
Remember the order of cases and how where clauses filter values.
Predict Output
intermediate
2: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")
}
AOn the diagonal
BAbove the diagonal
CUnknown
DBelow the diagonal
Attempts:
2 left
💡 Hint
Compare x and y values carefully.
🔧 Debug
advanced
2: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")
}
AMissing default case
BCannot use let binding in switch cases
CMissing colon ':' after the first case's where clause
DCannot use comparison operators in where clause
Attempts:
2 left
💡 Hint
Check punctuation after case statements.
🚀 Application
advanced
2: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")
}
AAdult
BTeenager
CSenior
DInvalid age
Attempts:
2 left
💡 Hint
Check which age range 20 falls into.
🧠 Conceptual
expert
3: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")
}
APrints "Greater than 5" because the first matching case is executed
BPrints "Greater than 3" because it is the more specific condition
CPrints "3 or less" because default always runs
DCompilation error due to overlapping where clauses
Attempts:
2 left
💡 Hint
Switch executes the first matching case only.