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

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

主站蜘蛛池模板: 通榆县| 隆林| 嵊州市| 凉城县| 樟树市| 宁国市| 饶河县| 中阳县| 平泉县| 灵石县| 玛多县| 尼勒克县| 新河县| 色达县| 应城市| 泰顺县| 东丽区| 思南县| 凤山县| 通化县| 夹江县| 浙江省| 天镇县| 云梦县| 泸水县| 建瓯市| 禄丰县| 克东县| 麻城市| 岳普湖县| 长宁区| 麦盖提县| 镇赉县| 嵊州市| 柘荣县| 渝北区| 八宿县| 梅州市| 双峰县| 临沧市| 桂平市|