Switch in Swift can be seen as a combination of if statements. Indeed, Swift takes the value of a variable or constant and then compares it to multiple cases until it founds the one that is true. Once it found the one, it will execute the code related to it and doesn’t continue with the other cases.
Switch has the following structure. Each case needs to have its own statement or else an error will incur. When using switch we either state all the cases that are possible or we state those that we know and we put a default case at the end. The default case will be executed only if all the above cases were false.
So let’s take a simple example, in order to better visualise. So we will declare a String constant “color” and give it the value “red”. Then we will create several cases which will test if the color is the one stated by the case. When we will find the color, the code that relates to that case will be executed.
Switch case – Intervals
It is also possible to create cases that include an interval and this may be very practical when dealing with numbers.
So our average constant will be compared to a range of numbers. If the number is included in that range then the code related to that case will be executed.
Switch case – multiple values
Another option is to have multiple values which are part of the same case. Let’t write a little code that will tell us if our constant is an odd or an even number.
In this example, the odd constant has a value of 1 which corresponds with one of the values of the second case, thus the statement of the second case will be executed and it will tell us that our constant is an odd number.
Switch case – where clause
We can also have cases that include the where function. This means that each case will have a condition that must be respected in order to execute the code related to it. To visualise better, let’s develop our previous example and include an where clause.