Latest web development tutorials

Swift switch statement

Swift conditional statement Swift conditional statement

switch statement allows a variable equal to a plurality of test value.Swift language? Just match the case statement, the statement is executed to complete the entire switch.


grammar

Swift language switch statement syntax:

switch expression {
   case expression1  :
      statement(s)
      fallthrough /* 可选 */
   case expression2, expression3  :
      statement(s)
      fallthrough /* 可选 */
  
   default : /* 可选 */
      statement(s);
}

Generally not used in the switch statement fallthrough statement.

Here we need to pay attention to case statement if nofallthrough statements, after the execution of the current case statement switch is terminated, the control flow jumps to the next line after the switch statement.

If thefallthrough statement will continue with case or default statement after the execution regardless of whether the conditions are satisfied.

Note: In most languages, switch statement block in case you want to keep up with break, or else run the statement after the order case, and in Swift language, the default is not execute down, switch will terminate.If you want to make the statement in the Swift case would continue to run after the order, we need to use fallthrough statement.

Example 1

The following examples are not using fallthrough statement:

import Cocoa

var index = 10

switch index {
   case 100  :
      print( "index 的值为 100")
   case 10,15  :
      print( "index 的值为 10 或 15")
   case 5  :
      print( "index 的值为 5")
   default :
      print( "默认 case")
}

When the above code is compiled executed, it will produce the following results:

index 的值为 10 或 15

Example 2

The following example uses fallthrough statement:

import Cocoa

var index = 10

switch index {
   case 100  :
      print( "index 的值为 100")
      fallthrough
   case 10,15  :
      print( "index 的值为 10 或 15")
      fallthrough
   case 5  :
      print( "index 的值为 5")
   default :
      print( "默认 case")
}

When the above code is compiled executed, it will produce the following results:

index 的值为 10 或 15
index 的值为 5

Swift conditional statement Swift conditional statement