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

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.

主站蜘蛛池模板: 田东县| 曲麻莱县| 黎平县| 常德市| 绥宁县| 宁明县| 铜鼓县| 桦南县| 隆化县| 阳新县| 阜南县| 宜黄县| 天气| 获嘉县| 张家口市| 玉屏| 常熟市| 定日县| 丹东市| 嘉鱼县| 固阳县| 班玛县| 略阳县| 灵宝市| 黄浦区| 韶关市| 延庆县| 石首市| 泸溪县| 新龙县| 武平县| 兴国县| 兰坪| 柳河县| 宁河县| 天门市| 临桂县| 永年县| 宽城| 班玛县| 公主岭市|