Challenge - 5 Problems
Swift Switch Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Swift switch statement?
Consider the following Swift code. What will it print when number = 2?
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
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 explicitly told to with 'fallthrough'. So only 'Two' is printed.
🧠 Conceptual
intermediate1:30remaining
Why does Swift require explicit 'fallthrough' in switch statements?
Why did Swift designers choose to disallow implicit fallthrough in switch statements?
Attempts:
2 left
💡 Hint
Think about common bugs in other languages caused by missing breaks.
✗ Incorrect
Implicit fallthrough can cause bugs when a programmer forgets to add a break statement. Swift avoids this by requiring explicit 'fallthrough', making code safer and clearer.
🔧 Debug
advanced2:00remaining
Identify the error in this Swift switch code
What error will this Swift code produce?
Swift
let value = 3 switch value { case 1: print("One") case 2: print("Two") case 3: print("Three") fallthrough case 4: print("Four") }
Attempts:
2 left
💡 Hint
Swift switch statements must be exhaustive.
✗ Incorrect
Swift requires all switch statements to be exhaustive, meaning every possible value must be handled. This switch only covers 1-4, but Int can have other values, causing a compile error (typically fixed with a 'default' case).
❓ Predict Output
advanced1:30remaining
What is the output when 'fallthrough' is omitted?
What will this Swift code print?
Swift
let x = 1 switch x { case 1: print("Start") case 2: print("Middle") case 3: print("End") default: print("Default") }
Attempts:
2 left
💡 Hint
Remember Swift does not fall through cases unless told.
✗ Incorrect
Without 'fallthrough', only the matching case runs. So only 'Start' is printed.
🧠 Conceptual
expert2:30remaining
How does Swift's switch design improve code clarity compared to C?
Which statement best explains how Swift's lack of implicit fallthrough in switch statements improves code clarity compared to C?
Attempts:
2 left
💡 Hint
Think about how forgetting 'break' in C can cause bugs.
✗ Incorrect
In C, forgetting 'break' causes unintended fallthrough bugs. Swift requires explicit 'fallthrough', so the code's behavior is clear and intentional, improving readability and reducing errors.