Switch statements
Another way to control flow is through the use of a switch statement, which lets you execute different bits of code depending on the value of a variable or constant.
Here’s a very simple switch statement that acts on an integer:
let number = 10
switch number { case 0:
print("Zero") default:
print("Non-zero")
}
In this example, the code will print the following:
Non-zero
The purpose of this switch statement is to determine whether or not a number is zero. It will get more complex — I promise!
To handle a specific case, you use case followed by the value you want to check for, which in this case is 0. Then, you use default to signify what should happen for all other values.
Here’s another example:
let number = 10
switch number { case 10:
print("It's ten!") default:
break
}
This time you check for 10, in which case, you print a message. Nothing should happen for other values. When you want nothing to happen for a case, or you want the default state to run, you use the break statement. This tells Swift that you meant to not write any code here and that nothing should happen. Cases can never be empty, so you must write some code, even if it’s just a break!
Of course, switch statements also work with data types other than integers. They work with any data type! Here’s an example of switching on a string:
let string = "Dog"
switch string { case "Cat", "Dog":
print("Animal is a house pet.") default:
print("Animal is not a house pet.")
}
This will print the following:
Animal is a house pet.
In this example, you provide two values for the case, meaning that if the value is equal to either "Cat" or "Dog", then the statement will execute the case.