The document discusses using phantom types to represent state in a class. A HogeOperation class is defined with a generic State parameter constrained to an OperationState protocol. Extensions are used to provide state-specific functionality based on the State. This allows initializing an operation in an Init state, transitioning it to a Prepared state where additional methods become available, and avoiding errors from calling methods associated with invalid states. The phantom types encode state without runtime representation, catching errors at compile-time.
63. // 設定項目を、初期値を持った構造体で用意して…
struct Description {
var channel: Int = default
var volume: Int = default
var pan: Int = default
var format: Format = default
var route: Route = default
}
86. let sub: Base = Sub()
let base: Base = Base()
// 実体が Sub なので、全ての機能が使える
let obj: Sub = unsafeBitCast(sub, to: Sub.self)
// 実体が Base なので、Sub の機能を使うとクラッシュする
let obj: Sub = unsafeBitCast(base, to: Sub.self)
87.
88.
89. class Test: OperationState {}
extension HogeOperation where State: Test {
func testSomething() {…}
}
extension HogeOperation where State: Init {
func testing() -> HogeOperation<Test> {…}
}
90.
91. // Test 状態を Prepared から継承させれば…
class Test: Prepared {}
// Test には Prepared の機能も備わる
extension HogeOperation where State: Prepared {
func execute() {…}
}
extension HogeOperation where State: Test {
func testSomething() {…}
}