为什么在swift中不允许使用开关盒的概念?

时间:2016-08-01 04:26:57

标签: ios swift switch-statement

var index = 30

switch index {

   case 10  :    
      println( "Value of index is 10")
   case 20  :

   case 30  :    
      println( "Value of index is either 20 or 30")
   case 40  :    
      println( "Value of index is 40")
   default :    
      println( "default case")
}

2 个答案:

答案 0 :(得分:5)

Swift允许使用Fallthrough,但you do have to state it explicitly

switch index {
case 10:
    println( "Value of index is 10")
case 20:
    fallthrough
case 30:
    println( "Value of index is either 20 or 30")
...

对于您的情况,最好只分组您的案例:

switch index {
case 10:
    println( "Value of index is 10")
case 20, 30:
    println( "Value of index is either 20 or 30")
...

答案 1 :(得分:1)

或者你可以这样写(Swift 2.2语法):

switch index {
case 10:
    print("Value is: \(index)")
case 20, 30:
    print("Value is: \(index)")
default:
    print("Default value is: \(index)")
}