Swift Switch語句

2019-10-16 23:14:23

當第一個匹配的情況(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