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

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.

主站蜘蛛池模板: 政和县| 平顺县| 虹口区| 互助| 株洲市| 高密市| 临江市| 道真| 巴楚县| 大竹县| 鄢陵县| 宜春市| 磐安县| 天津市| 南郑县| 镇康县| 庆元县| 青铜峡市| 若羌县| 开化县| 大邑县| 嘉义县| 伊川县| 西乡县| 大化| 长春市| 得荣县| 恭城| 霸州市| 庆云县| 高陵县| 兴安盟| 七台河市| 深泽县| 长丰县| 芜湖市| 广饶县| 鹤山市| 鹤壁市| 德格县| 庆云县|