0
0
Swiftprogramming~20 mins

Switch statement power in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Switch Statement Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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")
}
AOn the line x == y
BJust a point
CCompilation error
DOn the line x == -y
Attempts:
2 left
💡 Hint
Check the conditions in the where clauses carefully.
Predict Output
intermediate
2: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")
}
A
Two or Three
Four
BTwo or Three
CFour
DOther
Attempts:
2 left
💡 Hint
Remember what fallthrough does in Swift switch statements.
🔧 Debug
advanced
2: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")
}
AThe case _: syntax is invalid; it should be default.
BThe range 1..<5 overlaps with 5 causing ambiguity.
CThe switch cases are not exhaustive.
DThe case _: is unreachable because previous cases cover all values.
Attempts:
2 left
💡 Hint
Check the syntax for the default case in Swift switch statements.
Predict Output
advanced
2: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")
}
ALowercase vowel
BUppercase vowel
CCompilation error
DConsonant
Attempts:
2 left
💡 Hint
Check the placement of the where clause with multiple patterns.
Predict Output
expert
3: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)")
}
ASuccess with code <= 40
BSuccess with code > 40
CFailure: 42
DCompilation error
Attempts:
2 left
💡 Hint
Look at the associated value and the where clause condition.