In this tutorial you will learn about the Swift Switch Case and its application with practical example.
Swift Switch Case Statement
The switch statement is simplified form of the nested if … else if statement , it helps to avoid long chain of if..else if..else statements. A switch statement evaluates an expression against multiple cases in order to identify the block of code to be executed.
Swift Switch Case Flow Diagram
Syntax:-
1 2 3 4 5 6 7 8 |
switch expression { case value1: // statements case value2: // statements default: // statements } |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
let dayOfWeek:Int = 5 print("W3Adda - Swift switch statement.") switch dayOfWeek { case 1: print("Today is Monday.") case 2: print("Today is Tuesday.") case 3: print("Today is Wednesday.") case 4: print("Today is Thursday.") case 5: print("Today is Friday.") case 6: print("Today is Saturday.") case 7: print("Today is Sunday.") default: print("Invalid Weekday.") } |
In the above swift program we have an integer constant dayOfWeek with initial value of 5, and we pass this variable as expression to following switch statement, value of dayOfWeek is tested with multiple cases to identify the block of code to be executed.
When we run the above swift program, will see the following output –
Output:-