我可以声明一个变量“<”或“>”而不是以下switch语句中的某个数字吗?
var a = 150
switch a {
case 10...50:
print ("the value is 10 to 50")
fallthrough
case 100...125:
print ("the value is 100 to 125")
case 125...150:
print ("the value is 125 to 150")
default:
print ("the value is unknown")
}
是的,您可以使用where
子句检查switch语句中的其他条件。
var a = 150
var x = 250
switch a {
case _ where a > x:
print ("a is greater than x")
case _ where a < x:
print ("a is less than x")
default:
print ("a is equal to x")
}
或者您可以使用One sided range operator
检查数字是大于还是小于特定数字
switch a {
case ...50:
print ("the value is less than 50")
case 100...125:
print ("the value is 100 to 125")
case 125...:
print ("the value greater than 125")
default:
print ("the value is unknown")
}
当然你可以在switch语句中声明一个<或>某个数字的变量,但我不认为这就是你的意思。
我想你真的想问一下你是否可以在案例评估中使用<或>。是的,你可以使用where
条款来做到这一点。
所以,你可以做到这一点,例如:
var a = 150
let b = 160
switch a {
case 10...50 where b < a: print ("the value is 10 to 50 and b < a")
case 100...125 where b == a: print ("the value is 100 to 125 and b == a")
case 125...150 where b > a: print ("the value is 125 to 150 and b > a")
default: print ("default")
}
这将打印:
值为125到150,b> a
您可以在Swift文档中阅读有关Swift switch语句的更多信息:
https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html