当我执行此代码时,只有 print("it is greater than zero")
被执行,但我有两种情况是正确的,我尝试使用 fallthrough
关键字,但它会执行下一个 case block ,即使它为 false,无论如何,
这又引出了另一个问题,什么时候应该使用 fallthrough
关键字?如果我想强制执行下一个 block ,为什么不将代码插入到 fallthrough
所在的同一 block 中?
有没有什么方法可以让下面的示例打印所有计算结果为真的情况并仍然排除所有计算结果为假的情况?
let number = 1
switch number {
case _ where number > 0:
print("it is greater than zero")
case _ where number < 2:
print("it is less than two")
case _ where number < 0:
print("it is less than zero")
default:
print("default")
}
预先感谢您的回答!
最佳答案
switch
语句不是为了这个目的,也不是这样工作的。它的目的是找到一个真实的案例。如果你想检查多个案例,那只是一个 if
语句:
let number = 1
if number > 0 {
print("it is greater than zero")
}
if number < 2 {
print("it is less than two")
}
if number < 0 {
print("it is less than zero")
}
对此没有等效的开关
。它们是不同的控制语句。
正如您所发现的,fallthrough
的存在允许两个案例运行同一个 block 。这就是它的用途;它不检查其他情况。通常,如果你广泛使用 case _
,你可能没有在 Swift 中正确使用 switch
,应该使用 if
。
关于swift - 如何使用 where 关键字快速检查 switch 语句中的所有情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53290475/