- 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高可用解決方案:從主從復制到InnoDB Cluster架構
- Effective Amazon Machine Learning
- Oracle RAC 11g實戰指南
- 醫療大數據挖掘與可視化
- 算法與數據中臺:基于Google、Facebook與微博實踐
- 企業級數據與AI項目成功之道
- 數字媒體交互設計(初級):Web產品交互設計方法與案例
- 信息學競賽寶典:數據結構基礎
- Hadoop集群與安全
- 大數據時代系列(套裝9冊)
- 云計算
- 利用Python進行數據分析(原書第2版)
- Microsoft Dynamics NAV 2015 Professional Reporting
- 一本書讀懂大數據
- MySQL性能調優與架構設計