fallthrough statement
优质
小牛编辑
149浏览
2023-12-01
一旦第一个匹配的情况完成,Swift 4中的switch语句就完成了它的执行,而不是像C和C ++编程语言中那样落入后续情况的底部。
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语句中。
语法 (Syntax)
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 (Example 1)
以下示例显示如何在Swift 4编程中使用switch语句without 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 (Example 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