- 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.
推薦閱讀
- MySQL高可用解決方案:從主從復制到InnoDB Cluster架構
- 在你身邊為你設計Ⅲ:騰訊服務設計思維與實戰
- 程序員修煉之道:從小工到專家
- Unity 5.x Game AI Programming Cookbook
- Word 2010中文版完全自學手冊
- Voice Application Development for Android
- Apache Kylin權威指南
- 企業級容器云架構開發指南
- 淘寶、天貓電商數據分析與挖掘實戰(第2版)
- IPython Interactive Computing and Visualization Cookbook(Second Edition)
- Chef Essentials
- MySQL DBA修煉之道
- Python數據分析從小白到專家
- Access 2010數據庫程序設計實踐教程
- Python 3爬蟲、數據清洗與可視化實戰