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迴圈語句