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

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.

主站蜘蛛池模板: 达拉特旗| 南华县| 辽宁省| 汽车| 库车县| 乐都县| 汶川县| 灵寿县| 德钦县| 鄂托克前旗| 阿拉善左旗| 镇安县| 绍兴县| 松桃| 湖南省| 准格尔旗| 雅安市| 图片| 新沂市| 上思县| 乌鲁木齐市| 翼城县| 迭部县| 元氏县| 涞水县| 深泽县| 黄大仙区| 区。| 安平县| 抚顺县| 利辛县| 即墨市| 鲁山县| 鱼台县| 林口县| 东乌珠穆沁旗| 长泰县| 淳化县| 眉山市| 辽阳县| 长武县|