Swift 3.0 Switch语句没有默认语句get error 'Switch必须是详尽的,考虑添加默认条款'

时间:2022-08-19 17:18:20

Following is the code used for executing Switch statement in playground. I executed few switch statements without using default. My doubt is why it is optional for some and mandatory for other statements.Thanks in advance!.

下面是用于在操场上执行Switch语句的代码。在没有使用默认值的情况下,我执行了很少的switch语句。我的疑问是为什么它是可选的,对于其他的声明是强制性的。提前谢谢!

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

 }

Counter statement executed successfully without using default

计数器语句成功执行,不使用默认值。

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

   }

1 个解决方案

#1


6  

As other stated in comments, you should use default because in your cases you're not exposing every possible Double. But if you like more the way you did it in your second example you could do it like so:

正如其他在注释中所述,您应该使用默认值,因为在您的案例中,您没有公开所有可能的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)")
}

Just for the reference, here's how this scenario is most often handled:

仅供参考,以下是该场景最常用的处理方式:

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

#1


6  

As other stated in comments, you should use default because in your cases you're not exposing every possible Double. But if you like more the way you did it in your second example you could do it like so:

正如其他在注释中所述,您应该使用默认值,因为在您的案例中,您没有公开所有可能的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)")
}

Just for the reference, here's how this scenario is most often handled:

仅供参考,以下是该场景最常用的处理方式:

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