3 min readJan 20, 2026
SwiftHow to Use Switch in Swift
Match values safely with exhaustive switch cases.
Steps
- Paste the code into a Swift file or playground.
- Run it once to verify the output.
- Adjust the inputs to match your use case.
Copy and paste
import Foundation
let status = 404
switch status {
case 200:
print("OK")
case 400...499:
print("Client error")
case 500...599:
print("Server error")
default:
print("Unknown")
}Notes
- Keep functions small and focused for reuse.
- Prefer safe APIs like optionals and guards.
