官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 博湖县| 双峰县| 利川市| 阿克陶县| 辽阳市| 宿松县| 河北省| 星座| 民和| 海晏县| 文山县| 江津市| 台东市| 西林县| 商丘市| 行唐县| 甘洛县| 白城市| 手游| 礼泉县| 霍州市| 平邑县| 宽甸| 宜章县| 化隆| 闽侯县| 临沧市| 许昌县| 茂名市| 永靖县| 长丰县| 林州市| 大足县| 三台县| 连州市| 敦煌市| 泾源县| 辽中县| 临泉县| 封丘县| 五河县|