Ram*_*Ram -1 switch-statement swift3
以下是用于在playground中执行Switch语句的代码.我执行了几个switch语句而没有使用default.我怀疑的是为什么它对某些人来说是可选的而且对于其他陈述是强制性的.谢谢提前!
let someNumber = 3.5
switch someNumber {
case 2 , 3 , 5 , 7 , 11 , 13 :
print("Prime numbers")
case 4 , 6 , 24 , 12 , 66 :
print("Normal numbers")
}
Run Code Online (Sandbox Code Playgroud)
计数器语句在不使用默认值的情
let yetAnotherPoint = (3,1)
switch yetAnotherPoint {
case let (x,y) where x == y :
print("(\(x),\(y)) is on the line x == y")
case let (x,y) where x == -y :
print("(\(x),\(y)) is on the line x == -y")
case let (x,y):
print("(\(x),\(y)) is just some arbitrary point")
}
Run Code Online (Sandbox Code Playgroud)
正如评论中所述,您应该使用,default因为在您的情况下,您不会暴露所有可能的Double.但是如果你更喜欢你在第二个例子中所做的那样,你可以这样做:
let someNumber = 3.5
switch someNumber {
case 2 , 3 , 5 , 7 , 11 , 13 :
print("Prime numbers")
case 4 , 6 , 24 , 12 , 66 :
print("Normal numbers")
case let x:
print("I also have this x = \(x)")
}
Run Code Online (Sandbox Code Playgroud)
仅供参考,以下是最常处理此场景的方法:
let someNumber = 3.5
switch someNumber {
case 2 , 3 , 5 , 7 , 11 , 13 :
print("Prime numbers")
case 4 , 6 , 24 , 12 , 66 :
print("Normal numbers")
default:
print("I have an unexpected case.")
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6554 次 |
| 最近记录: |