As we saw in the article Control Flow I, we can check a series of related conditions using if, else, and else if.
For example, we can store the status of a shipment in a variable of type String and display a message in the console based on that status.
var shipmentState: String = "SENT"
if shipmentState == "PREPARING" {
print("The package is being prepared")
}
else if shipmentState == "SENT" {
print("The package has been sent")
}
else if shipmentState == "IN_DELIVERY" {
print("The package is out for delivery")
}
else if shipmentState == "DELIVERED" {
print("The package has been delivered")
}
else {
print("No shipping information available")
}
// The console shows: The package has been sent
However, this can also be done using a switch. The functionality is as follows:
- Specify the variable to analyze.
- Define what to do in each case.
- Define what to do if none of the cases match with keyword
default
.
var shipmentState: String = "SENT"
switch shipmentState {
case "PREPARING":
print("The package is being prepared")
case "SENT":
print("The package has been sent")
case "IN_DELIVERY":
print("The package is out for delivery")
case "DELIVERED":
print("The package has been delivered")
default:
print("No shipping information available")
}
// The console shows: The package has been sent
As you can see, the switch command analyzes the value of shipmentState
and executes only the case
that matches that value.
It is necessary to cover all cases
The switch command requires us to cover all cases. In our example, a String can have infinite combinations, so we must include the default
case, which will execute if none of the other cases match.
Executing the same code for multiple cases
If we need to execute exactly the same code for more than one case, we can define those cases separated by commas, thus avoiding code repetition.
var shipmentState: String = "SENT"
switch shipmentState {
case "PREPARING":
print("The package is being prepared")
case "SENT", "IN_DELIVERY":
print("The package is on its way")
case "DELIVERED":
print("The package has been delivered")
default:
print("No shipping information available")
}
// The console shows: The package is on its way
Be the first to comment