Swift — Switch
Basic switch
let day = "Monday"
switch day {
case "Monday":
print("Start of week")
case "Friday":
print("Almost weekend")
case "Saturday", "Sunday":
print("Weekend!")
default:
print("Midweek")
}
Range matching
let score = 85
switch score {
case 90...100:
print("A")
case 80..<90:
print("B")
case 70..<80:
print("C")
default:
print("F")
}
Tuple matching
let point = (1, 1)
switch point {
case (0, 0):
print("Origin")
case (_, 0):
print("On x-axis")
case (0, _):
print("On y-axis")
case (-2...2, -2...2):
print("Inside 2x2 box")
default:
print("Outside")
}
Value binding
let anotherPoint = (2, -2)
switch anotherPoint {
case let (x, y) where x == y:
print("On line x == y")
case let (x, y) where x == -y:
print("On line x == -y")
case let (x, y):
print("Somewhere else at (\(x), \(y))")
}
where clause
let temperature = 35
switch temperature {
case 0...10:
print("Cold")
case 11...25:
print("Mild")
case 26...35 where temperature > 30:
print("Very hot")
default:
print("Hot")
}
Enum matching
enum HttpStatus: Int {
case ok = 200
case notFound = 404
case serverError = 500
}
let status = HttpStatus.notFound
switch status {
case .ok:
print("Success")
case .notFound:
print("Not found")
case .serverError:
print("Server error")
}
Exhaustive checking
// Swift requires exhaustive switching
// Missing cases cause compile error
enum Coin { case heads, tails }
let coin = Coin.heads
switch coin {
case .heads:
print("Heads")
case .tails:
print("Tails")
// All cases covered - no default needed
}
Mini Practice
Write Swift code that:
- Uses
switchwith ranges and tuples - Adds a
whereclause to a switch case - Pattern matches an enum
- Demonstrates exhaustive switching
Up Next
In the next lesson, you'll learn about Loops — for, while, and iteration in Swift.
Related Topics
Frequently Asked Questions about Switch
What is Switch in Swift?
Switch is a fundamental concept in Swift. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Switch?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Switch.
Why is Switch important in Swift?
Switch is essential for Swift development. Understanding this concept will help you write better code and solve real-world problems more effectively.