如何在Swift中编写一个空案例?

时间:2014-06-08 16:07:32

标签: swift

由于swift不会在case中声明switch语句,如何在不收到错误的情况下编写空的case语句?

let a = 50
switch a {
case 0..10:
case 10..100:
    println("between 10 and 100")
default:
    println("100 and above")
}

如何让第一种情况停止开关?

2 个答案:

答案 0 :(得分:74)

let a = 50
switch a {
case 0..10:
    break // Break the switch immediately
case 10..100:
    println("between 10 and 100")
default:
    println("100 and above")
}

关键字break是可选的,但不在此案例中:)

答案 1 :(得分:28)

为防止错误:

Case label in a switch should have at least one executable statement

...在案例标签中使用(),如下例所示。也适用于default标签。

let a = 1
switch a {
case 1:
    ()
case 2:
    println("2")
default:
    ()
}