上QQ阅读APP看书,第一时间看更新
Switching the state of light
With our final case, let's look at how to interpret the current state of the light:
switch state {
case .on:
doSomething()
case .off:
doSomething()
case .dimmed(let value):
switch value {
case .quarter:
doSomething()
case .half:
doSomething()
case .threeQuarters:
doSomething()
}
}
The switch statement in Swift is very different from the one in Objective-C. First, the cases do not fall through each other, so there's no need to add the break statement after each case.
If you want multiple cases to be handled with the same code, you can use the following strategy:
switch state {
case .on, .off:
doSomething()
default:
break
}
Falling through is somehow not encouraged in Swift, so always try to adapt your code in order not to leverage this. If you can't avoid it, the following code shows how it should be implemented:
switch state {
case .off:
doSomethingOff()
fallthrough
case .on:
doSomething()
default:
break
}
If state is off, both doSomethingOff and doSomething will be called. If state is on, only doSomething will be called.