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