Upgrade to Pro — share decks privately, control downloads, hide ads and more …

phantom type

phantom type

👻

to4iki

May 21, 2017
Tweet

More Decks by to4iki

Other Decks in Programming

Transcript

  1. ঢ়ଶຖͷػೳΛઃܭ͢Δ // ܕύϥϝʔλͰঢ়ଶΛද͢ class HogeOperation<State: OperationState> {} // ঢ়ଶຖʹػೳΛઃܭ͢Δ extension

    HogeOperation where State == Init { func prepared() -> HogeOperation<Prepared> { return HogeOperation<Prepared>() } } extension HogeOperation where State == Prepared { func execute() { print("do something") } }
  2. ঢ়ଶʹԠͯ͡ɺػೳ͕੾ΓସΘΔ // ४උঢ়ଶ let operation = HogeOperation<Init>() operation.execute() // compile

    error // ४උ׬ྃঢ়ଶ let preparedOperation = operation.prepared() preparedOperation.execute() preparedOperation.prepared() // compile error
  3. ࣄલ࣮ߦΛڧ੍͢ΔBuilder // builderͷঢ়ଶ protocol BuilderState {} class Buildable: BuilderState {}

    class Unbuildable: BuilderState {} class UserBuilder<Name: BuilderState, Age: BuilderState> { fileprivate let name: String fileprivate let age: UInt private init(name: String, age: UInt) { self.name = name self.age = age } static var builder: UserBuilder<Unbuildable, Unbuildable> { return UserBuilder<Unbuildable, Unbuildable>(name: "", age: 0) } func set(name: String) -> UserBuilder<Buildable, Age> { return UserBuilder<Buildable, Age>(name: name, age: age) } func set(age: UInt) -> UserBuilder<Name, Buildable> { return UserBuilder<Name, Buildable>(name: name, age: age) } }
  4. ࣄલ࣮ߦΛڧ੍͢ΔBuilder struct User { let name: String let age: UInt

    } // NameͱAge͕Buildableͷ࣌ extension UserBuilder where Name: Buildable, Age: Buildable { funsc build() -> User { return User(name: name, age: age) } }
  5. ࣄલ࣮ߦΛڧ੍͢ΔBuilder let builder = UserBuilder<Unbuildable, Unbuildable>.builder builder.set(name: "hoge").build() // compile

    error builder.set(age: 10).build() // compile error let user = builder .set(name: "hoge") .set(age: 10) .build()