Swift Fallthrough語句

2019-10-16 23:14:16

當第一個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 yiibai. 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