Challenge - 5 Problems
Swift Switch Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of switch without explicit fallthrough
What will be the output of this Swift code snippet?
Swift
let number = 2 switch number { case 1: print("One") case 2: print("Two") case 3: print("Three") default: print("Other") }
Attempts:
2 left
💡 Hint
Remember that Swift switch cases do not fall through by default.
✗ Incorrect
In Swift, each case in a switch statement is exclusive and does not continue to the next case unless you explicitly use the 'fallthrough' keyword. So only 'Two' is printed.
❓ Predict Output
intermediate2:00remaining
Effect of fallthrough keyword in Swift switch
What will be printed when this Swift code runs?
Swift
let value = 1 switch value { case 1: print("Start") fallthrough case 2: print("Middle") case 3: print("End") default: print("Default") }
Attempts:
2 left
💡 Hint
Check what the 'fallthrough' keyword does in Swift switch cases.
✗ Incorrect
The 'fallthrough' keyword causes execution to continue to the next case without checking its condition. So 'Start' and then 'Middle' are printed.
🔧 Debug
advanced2:00remaining
Why does this Swift switch code not compile?
Identify the reason this Swift code causes a compile error.
Swift
let x = 5 switch x { case 1: print("One") case 2: print("Two") case 3: print("Three") }
Attempts:
2 left
💡 Hint
Swift switch statements must be exhaustive for non-enum types.
✗ Incorrect
Since x is an Int, the switch must cover all possible values or include a default case. Missing default causes a compile error.
🧠 Conceptual
advanced2:00remaining
Understanding no implicit fallthrough in Swift switch
Which statement best describes Swift's switch behavior regarding fallthrough?
Attempts:
2 left
💡 Hint
Think about how Swift differs from C-like languages in switch behavior.
✗ Incorrect
Swift requires explicit 'fallthrough' to continue to the next case. Without it, execution stops after the matched case.
🚀 Application
expert3:00remaining
Predict the output with multiple fallthroughs in Swift switch
What is the output of this Swift code?
Swift
let n = 1 switch n { case 1: print("A") fallthrough case 2: print("B") fallthrough case 3: print("C") default: print("D") }
Attempts:
2 left
💡 Hint
Each fallthrough moves execution to the next case regardless of its condition.
✗ Incorrect
Starting at case 1, prints 'A', then fallthrough to case 2 prints 'B', then fallthrough to case 3 prints 'C'. Default is not reached.