當第一個匹配的情況(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 */
/* 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
語句。 我們將採用以下兩個範例來明確其功能。
以下是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
以下是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