Switch Statement in Swift

Suneet Agrawal
2 min readApr 12, 2022

--

The switch statement in Swift is used to execute a particular block of code based on multiple conditions. A switch statement is useful for more than one condition. For one or two conditions, if-else is a better option but for conditions more than that, a switch statement is a better option.

This post was originally posted at https://agrawalsuneet.github.io/blogs/switch-statement-in-swift/ and reposted on Medium on 12th April 2022.

We will try to understand the flow of switch statement in detail but let’s try to understand its basic syntax first.

The switch statement begins with a switch keyword followed by an expression based on which the cases will be evaluated.
The expression is followed by different cases and the code block for each case.
If none of the cases matches, the default block will be executed.
The basic syntax will look like below.

switch (expression)  {
case value1:
// statements
case value2:
// statements
...
...

default:
// statements
}

Let’s try to understand it with a flow chart before taking an example.
The below flow chart explains the basic flow of a switch statement which starts with an expression followed by cases. If the condition matches, the code block for that case will be executed. If non of the cases match, the default case will be executed.

Now let’s see an example for the switch statement.

let dayOfWeek = 2switch dayOfWeek {	    
case 1:
print("Monday")

case 2:
print("Tuesday")

case 3:
print("Wednesday")

case 4:
print("Thursday")

case 5:
print("Friday")

case 6:
print("Saturday")
case 7:
print("Sunday")

default:
print("Invalid day")
}
//this will print
//Monday

Things to notice here

Please continue reading at https://agrawalsuneet.github.io/blogs/switch-statement-in-swift/

That’s all for now. You can read my other interesting blogs here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

--

--