Javatpoint Logo
Javatpoint Logo

Swift Switch Statement

The Switch statement is used as a substitute for long if-else-if statement while matching complex patterns. It provides multiple cases to perform different actions according to different conditions.

Syntax:

Working of Switch statement in Swift

  • The switch statement goes top to bottom, takes expressions and compares with each case values.
  • If it matches the case, the statement inside the case is executed and the entire switch statement finishes its execution as soon as the first matching switch case is completed.
  • If there is no match for the case, it goes to the next case.
  • The default keyword is a code which runs if there is no case is matched.
Swift Switch Statement

Switch Statement Example

Output:

It is Friday today

In the above program, switch statement starts by matching dayOfWeek value with case 1. Since dayOfWeek value doesn't match the first case value 1, it falls to the next case until it finds the match. It finds the match in case 6, print the declaration and the switch statement terminates.

Switch statement with fallthrough in Swift

The fallthrough statement is used in switch statement if you want to proceed the control to next case.

Example

Output:

It is Thursday today
It is Friday today

In the above example, you can see that case 5 executes the statement print("It is Wednesday today") and fallthrough keyword proceeds to case6 which prints print("It is Thursday today").


Next TopicSwift if Statement





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA