- 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.
推薦閱讀
- ETL數據整合與處理(Kettle)
- 輕松學大數據挖掘:算法、場景與數據產品
- Test-Driven Development with Mockito
- 虛擬化與云計算
- 圖解機器學習算法
- 大數據算法
- WS-BPEL 2.0 Beginner's Guide
- Starling Game Development Essentials
- MySQL 8.x從入門到精通(視頻教學版)
- SQL優化最佳實踐:構建高效率Oracle數據庫的方法與技巧
- INSTANT Android Fragmentation Management How-to
- Spring Boot 2.0 Cookbook(Second Edition)
- 改進的群智能算法及其應用
- Scratch 2.0 Game Development HOTSHOT
- 大數據技術體系詳解:原理、架構與實踐