Bil*_*ain 144 switch-statement swift
斯威夫特是否会通过声明落空?例如,如果我做以下
var testVar = "hello"
var result = 0
switch(testVal)
{
case "one":
result = 1
case "two":
result = 1
default:
result = 3
}
Run Code Online (Sandbox Code Playgroud)
是否可以为案例"一"和案例"两个"执行相同的代码?
Cez*_*cik 352
是.你可以这样做:
var testVal = "hello"
var result = 0
switch testVal {
case "one", "two":
result = 1
default:
result = 3
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用fallthrough关键字:
var testVal = "hello"
var result = 0
switch testVal {
case "one":
fallthrough
case "two":
result = 1
default:
result = 3
}
Run Code Online (Sandbox Code Playgroud)
小智 8
var testVar = "hello"
switch(testVar) {
case "hello":
println("hello match number 1")
fallthrough
case "two":
println("two in not hello however the above fallthrough automatically always picks the case following whether there is a match or not! To me this is wrong")
default:
println("Default")
}
Run Code Online (Sandbox Code Playgroud)
case "one", "two":
result = 1
Run Code Online (Sandbox Code Playgroud)
没有中断声明,但案例更灵活.
附录:正如Analog File指出的那样,breakSwift中确实有声明.它们仍然可以在循环中使用,虽然在switch语句中是不必要的,除非你需要填充其他空的情况,因为不允许空的情况.例如:default: break.
这是您容易理解的示例:
let value = 0
switch value
{
case 0:
print(0) // print 0
fallthrough
case 1:
print(1) // print 1
case 2:
print(2) // Doesn't print
default:
print("default")
}
Run Code Online (Sandbox Code Playgroud)
结论:fallthrough当前一个fallthrough匹配或不匹配时,用于执行下一个情况(仅一个)。