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

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

主站蜘蛛池模板: 手机| 岫岩| 磐石市| 普安县| 文安县| 含山县| 南城县| 揭东县| 紫金县| 莱阳市| 揭西县| 博爱县| 晋州市| 红河县| 保靖县| 凤阳县| 吉木乃县| 虎林市| 博兴县| 铜陵市| 竹北市| 社旗县| 沙湾县| 乐陵市| 家居| 涪陵区| 通江县| 徐州市| 泽普县| 伊金霍洛旗| 景东| 江源县| 将乐县| 南陵县| 元阳县| 砚山县| 杂多县| 日喀则市| 屏东市| 明水县| 新干县|