Swift Fallthrough 语句

Swift 循环

Swift fallthrough 语句让 case 之后的语句会按顺序继续运行,且不论条件是否满足都会执行。

Swift 中的 switch 不会从上一个 case 分支落入到下一个 case 分支中。只要第一个匹配到的 case 分支完成了它需要执行的语句,整个switch代码块完成了它的执行。

注意:在大多数语言中,switch 语句块中,case 要紧跟 break,否则 case 之后的语句会顺序运行,而在 Swift 语言中,默认是不会执行下去的,switch 也会终止。如果你想在 Swift 中让 case 之后的语句会按顺序继续运行,则需要使用 fallthrough 语句。

语法

Swift fallthrough 语句的语法格式如下:

fallthrough

一般在 switch 语句中不使用 fallthrough 语句。

实例1

以下实例没有使用 fallthrough 语句:

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")
}

当上面的代码被编译执行时,它会产生下列结果:

index 的值为 10 或 15

实例2

以下实例使用 fallthrough 语句:

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")
}

当上面的代码被编译执行时,它会产生下列结果:

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

Swift 循环