迅速破案

迅捷有没有通过陈述? 例如,如果我这样做

var testVar = "hello"
var result = 0


switch(testVal)
{
case "one":
result = 1
case "two":
result = 1
default:
result = 3
}

有没有可能对情况“1”和情况“2”执行相同的代码?

53693 次浏览

是的,你可以这样做:

var testVal = "hello"
var result = 0


switch testVal {
case "one", "two":
result = 1
default:
result = 3
}

或者,您可以使用 fallthrough关键字:

var testVal = "hello"
var result = 0


switch testVal {
case "one":
fallthrough
case "two":
result = 1
default:
result = 3
}
case "one", "two":
result = 1

没有 break 语句,但案例更加灵活。

附录: 正如 Analog File 指出的,Swift 中实际上有 break语句。它们仍然可以在循环中使用,尽管在 switch语句中没有必要使用它们,除非您需要填充一个其他的空大小写,因为不允许使用空大小写。例如: default: break

案例结尾处的关键字 fallthrough会导致您正在寻找的漏洞行为,并且在一个案例中可以检查多个值。

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")
}

下面是一个很容易理解的例子:

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")
}

结论: 使用 fallthrough执行下一个案例(只有一个) ,前一个案例有 fallthrough是否匹配。