Understanding Swift Switch Statement
What is a Swift Switch Statement?
A switch
statement evaluates an expression against
multiple cases and executes the matching block of code. It is an
effective alternative to if-else
statements when
handling multiple conditions.
Key Benefits:
- Enhances code readability
-
More efficient than
if-else
for multiple conditions - Supports advanced features like pattern matching, value binding, and range matching
Syntax of a Switch Statement
switch
expression {
case value1:
// Code to execute
fallthrough
// Optional
case value2:
// Code to execute
break
// Optional
default:
// Default case if no match
}
Example 1: Basic Switch Statement in Swift
import
Foundation
let age = 25
switch age {
case 18:
print("You just became an adult!")
case 21:
print("You can legally drink!")
case 25:
print("You are in your mid-20s!")
default:
print("Age is just a number!")
}
Output
Break Statement in Switch
The break
statement terminates a switch case execution
immediately, preventing code from executing unintentionally.
import
Foundation
let day = 3
switch day {
case 1:
print("Monday")
break
case 2:
print("Tuesday")
break
case 3:
print("Wednesday")
break
case 4:
print("Thursday")
break
case 5:
print("Friday")
break
default:
print("Weekend")
}
Output
Fallthrough in Switch Statements
In Swift, switch cases do not fall through by default. If you want
execution to continue to the next case, use
fallthrough
explicitly.
import
Foundation
let num = 2
switch num {
case 1:
print("This is case 1")
fallthrough
case 2:
print("This is case 2")
fallthrough
case 3:
print("This is case 3")
default:
print("End of switch block")
}
Output
This is case 3
Using Ranges in Switch Statements
You can check if a value falls within a specific range using Swift’s range operators.
import
Foundation
let
temperature = 27
switch
temperature {
case ..<0:
print("Freezing cold")
case 0...20:
print("Cold")
case 21...30:
print("Moderate")
case 31...:
print("Hot")
default:
print("Invalid temperature")
}
Output
Tuple Matching in Switch Statements
Swift allows tuple matching to evaluate multiple values simultaneously.
import
Foundation
let
coordinates = (x: 5, y: 10)
switch
coordinates {
case (0, 0):
print("Origin point")
case (5, 10):
print("Point is at (5,10)")
default:
print("Point is somewhere else")
}
Output
Value Binding in Switch Statements
Value binding allows you to store case values as temporary variables within the case block.
import
Foundation
let number = 17
switch number {
case let
x where
x % 2 == 0:
print("\(x) is even")
case let
y where
y % 2 != 0:
print("\(y) is odd")
default:
print("Unknown number")
}
Output
Using the Where Clause in Switch Statements
The where
clause filters case conditions with
additional requirements. It allows you to add extra checks to a case
in a switch
statement.
Example
import
Foundation
let score = 77
switch score {
case 0...59:
print("Failed")
case 60...79
where score <
75:
print("Passed")
case 60...79
where score >=
75:
print("Passed with distinction")
case 80...100:
print("Excellent result!")
default:
print("Invalid score")
}
Output
Compound Cases in Swift Switch Statements
You can group multiple case values together to execute the same block of code. This is useful when multiple cases share the same logic.
Example
import
Foundation
let
luckyNumber = 7
switch
luckyNumber {
case 1, 3, 5, 7, 9:
print("You picked an odd number")
case 2, 4, 6, 8, 10:
print("You picked an even number")
default:
print("Number not in the list")
}