Latest web development tutorials

Swift Fallthrough statement

Swift cycle Swift cycle

Case statement to make after the Swift fallthrough statement will continue to run in sequence, and regardless of whether the conditions are satisfied to perform.

Swift does not fall into the switch from one branch to the next case a case branch. As long as a match to the first branch of the case statement is completed it needs to perform the entire switch code block finished its execution.

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.

grammar

Swift fallthrough statement syntax is as follows:

fallthrough

Generally not used in the switch statement 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 cycle Swift cycle