Swift switch statements are a powerful and flexible control flow mechanism. They allow developers to execute different code blocks based on multiple possible values of a variable or expression. Unlike some other languages, Swift's switch statements are more robust and feature-rich.
The basic syntax of a Swift switch statement is as follows:
switch someValue {
case value1:
// code to execute if someValue matches value1
case value2, value3:
// code to execute if someValue matches value2 or value3
default:
// code to execute if no other cases match
}
let dayNumber = 3
switch dayNumber {
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
case 4:
print("Thursday")
case 5:
print("Friday")
case 6:
print("Saturday")
case 7:
print("Sunday")
default:
print("Invalid day number")
}
// Output: Wednesday
let character = "a"
switch character {
case "a", "e", "i", "o", "u":
print("It's a vowel")
default:
print("It's a consonant")
}
// Output: It's a vowel
Swift switch statements can match ranges, making them ideal for grading systems or categorization tasks.
let score = 85
switch score {
case 0..<60:
print("Fail")
case 60..<70:
print("Pass")
case 70..<80:
print("Good")
case 80..<90:
print("Very Good")
case 90...100:
print("Excellent")
default:
print("Invalid score")
}
// Output: Very Good
Switch statements can match tuples, allowing for complex condition checking.
let point = (2, 0)
switch point {
case (0, 0):
print("Origin")
case (_, 0):
print("On the x-axis")
case (0, _):
print("On the y-axis")
case let (x, y) where x == y:
print("On the line x = y")
case let (x, y):
print("Point: (\(x), \(y))")
}
// Output: On the x-axis
To further enhance your understanding of control flow in Swift, explore these related topics:
By mastering switch statements, you'll have a powerful tool in your Swift programming arsenal for handling complex conditional logic efficiently and elegantly.