Swift’s switch, if case, and guard case support rich pattern matching—especially powerful with enums and tuples.
switch on enums
switch state {
case .idle:
print("waiting")
case .loaded(let count):
print("\(count) items")
case .failed(let message):
print(message)
}
Exhaustive switching—compiler errors if you miss a case when enums are closed.
where clauses and ranges
switch value {
case let x where x < 0: print("negative")
case 0: print("zero")
default: print("positive")
}
Important interview questions and answers
- Q: Exhaustive switch benefit?
A: Compiler forces handling new enum cases—safer refactors than stringly-typed state. - Q: if case vs switch?
A:if casematches one pattern inline—useful for single-case checks without full switch boilerplate.
Self-check
- Why must enum switches be exhaustive?
- How do you bind associated values in a case?
Tip: Exhaustive switch on enums catches new cases at compile time after refactors.
Interview prep
- Exhaustive switch?
Compiler requires all enum cases—safer refactors.
- if case?
Matches one pattern inline without full switch.