在 Swift 中的 switch 语句,只要第一个匹配的情况(case) 完成执行,而不是通过随后的情况(case)的底部,如它在 C 和 C++ 编程语言中的那样。以下是 C 和 C++ 的 switch 语句的通用语法:
语法
以下是 Swift 的 switch 语句的通用语法:
示例 1
以下是 Swift 编程 switch 语句中不使用 fallthrough 一个例子:
var index = 10
switch index {
case 100 :
println( "Value of index is 100")
case 10,15 :
println( "Value of index is either 10 or 15")
case 5 :
println( "Value of index is 5")
default :
println( "default case")
}
Value of index is either 10 or 15
示例 2
以下是 Swift 编程中 switch 语句带有 fallthrough 的例子:
var index = 10
switch index {
case 100 :
println( "Value of index is 100")
fallthrough
case 10,15 :
println( "Value of index is either 10 or 15")
fallthrough
case 5 :
println( "Value of index is 5")
default :
println( "default case")
}
Value of index is either 10 or 15 Value of index is 5