官术网_书友最值得收藏!

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

主站蜘蛛池模板: 双流县| 修水县| 台北市| 磴口县| 赤城县| 建宁县| 广水市| 六安市| 汝城县| 枣强县| 泰宁县| 崇州市| 乌拉特中旗| 仪征市| 乌鲁木齐县| 青海省| 黑水县| 策勒县| 汝州市| 洱源县| 东台市| 固镇县| 宁陵县| 遵化市| 宁陵县| 田林县| 东乌珠穆沁旗| 道孚县| 青神县| 龙州县| 赣榆县| 辛集市| 南通市| 武冈市| 莫力| 扬中市| 观塘区| 汝城县| 麦盖提县| 都江堰市| 乐平市|