- Hands-On Design Patterns with Swift
- Florent Vilmart Giordano Scalzo Sergio De Simone
- 109字
- 2021-07-02 14:44:58
Generic enums
In the following example, we will build a fully generic light:
enum State<T>: Equatable where T: Equatable {
case on
case off
case dimmed(T)
}
struct Bits8Dimming: Equatable {
let value: Int
init(_ value: Int) {
assert(value > 0 && value < 256)
self.value = value
}
}
struct ZeroOneDimming: Equatable {
let value: Double
init(_ value: Double) {
assert(value > 0 && value < 1)
self.value = value
}
}
let nostalgiaState: State<Bits8Dimming> = .dimmed(.init(10))
let otherState: State<ZeroOneDimming> = .dimmed(.init(0.4))
The dim type is now specified as a part of the State type. This gives us a lot of flexibility, as well as validation. Wrapping the value into a small struct adds very little overhead in terms of performance, and allows us to ensure that the values are sane before being set into our enum.
推薦閱讀
- MySQL數據庫進階實戰
- 漫話大數據
- 從零開始學Hadoop大數據分析(視頻教學版)
- Developing Mobile Games with Moai SDK
- 數據庫開發實踐案例
- 軟件成本度量國家標準實施指南:理論、方法與實踐
- Sybase數據庫在UNIX、Windows上的實施和管理
- SQL優化最佳實踐:構建高效率Oracle數據庫的方法與技巧
- 深入淺出 Hyperscan:高性能正則表達式算法原理與設計
- 大數據精準挖掘
- IPython Interactive Computing and Visualization Cookbook(Second Edition)
- 區塊鏈技術應用與實踐案例
- 云計算寶典:技術與實踐
- 數據庫查詢優化器的藝術:原理解析與SQL性能優化
- 數據挖掘與機器學習-WEKA應用技術與實踐(第二版)