企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# Swift switch 语句 **switch** 语句允许测试一个变量等于多个值时的情况。 Swift 语言中只要匹配到 case 语句,则整个 switch 语句执行完成。 ## 语法 Swift 语言中 switch 语句的语法: ``` switch expression { case expression1 : statement(s) fallthrough /* 可选 */ case expression2, expression3 : statement(s) fallthrough /* 可选 */ default : /* 可选 */ statement(s); } ``` 一般在 switch 语句中不使用 fallthrough 语句。 这里我们需要注意 case 语句中如果没有使用 **fallthrough** 语句,则在执行当前的 case 语句后,switch 会终止,控制流将跳转到 switch 语句后的下一行。 如果使用了**fallthrough** 语句,则会继续执行之后的 case 或 default 语句,不论条件是否满足都会执行。 > **注意:**在大多数语言中,switch 语句块中,case 要紧跟 break,否则 case 之后的语句会顺序运行,而在 Swift 语言中,默认是不会执行下去的,switch 也会终止。如果你想在 Swift 中让 case 之后的语句会按顺序继续运行,则需要使用 fallthrough 语句。 ### 实例1 以下实例没有使用 fallthrough 语句: ``` import Cocoa var index = 10 switch index { case 100 : print( "index 的值为 100") case 10,15 : print( "index 的值为 10 或 15") case 5 : print( "index 的值为 5") default : print( "默认 case") } ``` 当上面的代码被编译执行时,它会产生下列结果: ``` index 的值为 10 或 15 ``` ### 实例2 以下实例使用 fallthrough 语句: ``` import Cocoa var index = 10 switch index { case 100 : print( "index 的值为 100") fallthrough case 10,15 : print( "index 的值为 10 或 15") fallthrough case 5 : print( "index 的值为 5") default : print( "默认 case") } ``` 当上面的代码被编译执行时,它会产生下列结果: ``` index 的值为 10 或 15 index 的值为 5 ```