Swift Switch语句

当第一个匹配的情况(case)完成,Swift 4中的switch语句就会完成它的执行,而不是像CC++编程语言中那样落入后续case的底部。 以下是CC++switch语句的通用语法 -

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

   /* you can have any number of case statements */
   default : /* Optional */
      statement(s);
}

这里需要使用break语句跳来出一个case语句,否则执行控制将通过后续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循环语句