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

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.

主站蜘蛛池模板: 垫江县| 洱源县| 贵南县| 阿坝| 梅河口市| 承德市| 乐平市| 丰都县| 大英县| 高淳县| 华亭县| 东城区| 新闻| 北安市| 桐梓县| 庆安县| 无为县| 富平县| 东至县| 郁南县| 宁城县| 阿尔山市| 浑源县| 白山市| 克拉玛依市| 乌鲁木齐市| 井研县| 时尚| 夏邑县| 西青区| 常宁市| 蒙城县| 白水县| 东光县| 开封县| 通化县| 巫溪县| 九龙县| 翼城县| 乐山市| 阜城县|