switch statement
优质
小牛编辑
145浏览
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语句示例,不使用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