- Hands-On Design Patterns with Swift
- Florent Vilmart Giordano Scalzo Sergio De Simone
- 178字
- 2021-07-02 14:44:59
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.
推薦閱讀
- GitHub Essentials
- 數(shù)據(jù)庫(kù)原理及應(yīng)用教程(第4版)(微課版)
- Unity 5.x Game AI Programming Cookbook
- DB29forLinux,UNIX,Windows數(shù)據(jù)庫(kù)管理認(rèn)證指南
- 跟老男孩學(xué)Linux運(yùn)維:MySQL入門(mén)與提高實(shí)踐
- Oracle 12c云數(shù)據(jù)庫(kù)備份與恢復(fù)技術(shù)
- 數(shù)據(jù)庫(kù)技術(shù)實(shí)用教程
- Learn Selenium
- 一本書(shū)讀懂區(qū)塊鏈(第2版)
- 反饋:化解不確定性的數(shù)字認(rèn)知論
- 創(chuàng)新求索錄:第二集(精裝版)
- MySQL必知必會(huì)
- 數(shù)據(jù)隱私與數(shù)據(jù)治理:概念與技術(shù)
- SQL Server從入門(mén)到精通(第5版)
- Computer Programming for Absolute Beginners