Swift Fallthrough语句

当第一个case匹配完成,Swift 4中的switch语句就完成了它的执行,而不是像C和C++编程语言中那样落入后续case的底部。

C和C++中switch语句的通用语法如下 -

switch(expression){
   case constant-expression :
      statement(s);
      break; /* optional */
   case constant-expression :
      statement(s);
      break; /* optional */

   /* 可以有多个case语句 - by zaixian. com */
   default : /* Optional */
      statement(s);
}

在这里,在case语句中需要使用break语句,否则执行控制将落在匹配case语句下面的后续case语句中。

语法

Swift 4中switch语句的语法如下 -

switch expression {
   case expression1 :
      statement(s)
      fallthrough /* optional */
   case expression2, expression3 :
      statement(s)
      fallthrough /* optional */

   default : /* Optional */
      statement(s);
}

如果不使用fallthrough语句,那么程序将在执行匹配的case语句后退出switch语句。 这里将采用以下两个示例来明确它的功能。

示例1

以下示例显示如何在Swift 4编程中使用switch语句,但不使用fallthrough -

var index = 10

switch index {
   case 100 :
      print( "Value of index is 100")
   case 10,15 :
      print( "Value of index is either 10 or 15")
   case 5 :
      print( "Value of index is 5")
   default :
      print( "default case")
}

编译并执行上述代码时,会产生以下结果 -

Value of index is either 10 or 15

示例2

以下示例显示如何在Swift 4编程中使用switch语句 -

var index = 10

switch index {
   case 100 :
      print( "Value of index is 100")
      fallthrough
   case 10,15 :
      print( "Value of index is either 10 or 15")
      fallthrough
   case 5 :
      print( "Value of index is 5")
   default :
      print( "default case")
}

编译并执行上述代码时,会产生以下结果 -

Value of index is either 10 or 15
Value of index is 5

上一篇: Swift循环语句 下一篇: Swift字符串