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

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.

主站蜘蛛池模板: 贞丰县| 石狮市| 巨鹿县| 临沂市| 广德县| 太仆寺旗| 平顺县| 竹北市| 屯昌县| 大厂| 江西省| 越西县| 镇远县| 湾仔区| 鹰潭市| 雅安市| 新乡市| 纳雍县| 东乡族自治县| 富顺县| 旬邑县| 元阳县| 陕西省| 云南省| 长白| 法库县| 枣强县| 威宁| 白水县| 万年县| 溧水县| 库车县| 三亚市| 崇义县| 专栏| 威信县| 永丰县| 山丹县| 彭泽县| 镇康县| 淮南市|