Swift: Switch

Switch case

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.

Screen Shot 2017-04-15 at 18.17.33.png

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.

Screen Shot 2017-04-15 at 18.22.54.png

Switch case – Intervals

It is also possible to create cases that include an interval and this may be very practical when dealing with numbers.

Screen Shot 2017-04-15 at 18.29.03.png

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.

Screen Shot 2017-04-15 at 18.49.16.png

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.Screen Shot 2017-04-15 at 18.43.15.png

One thought on “Swift: Switch

Add yours

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: