Swift - Statement Switch Statement


You can use the Switch statement to replace a list of if-else statements.

The Switch statement has the following syntax:

switch variable/constant  {
    case value_1:
       statement (s)
    case value_2:
       statement (s)
    case value_n :
       statement (s)
      statement (s)

The value of the variable/constant is used for comparison with the various values specified ( value_1 , value2 , . . ., value_nn ).

If a match occurs, any statements following the value are executed specified using the case keyword.

If no match is found, any statements specified after the default keyword are executed.

Unlike C and Objective-C, there is no need to specify a Break statement after the last statement in each case.

Immediately after any statements in a case block are executed, the Switch statement finishes its execution.

In C, a Break statement is needed to prevent the statements after the current case from execution.

This behavior is known as implicit fallthrough.

In Swift, there is no implicit fallthrough: once the statements in a case are executed, the Switch statement ends.

Every Switch statement must be exhaustive.

The value that you are trying to match must be matched by one of the various cases in the Switch statement.

As it is sometimes not feasible to list all the cases, you would need to use the default case to match the remaining unmatched cases.

Related Topic