Skip to content

Instantly share code, notes, and snippets.

@lukesutton
Created June 15, 2017 06:28

Revisions

  1. lukesutton created this gist Jun 15, 2017.
    50 changes: 50 additions & 0 deletions state-machines.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    protocol Cancellable {}
    protocol Billable {}

    struct Initial: Cancellable {}
    struct Placed: Cancellable, Billable {}
    struct Billed: Cancellable {}
    struct Packed: Cancellable, Billable {}
    struct Shipped {}
    struct LostInTransit {}
    struct DamagedInTransit {}
    struct Cancelled {}

    struct Order<T> {

    }

    extension Order where T == Initial {
    var place: Order<Placed> {
    return Order<Placed>()
    }
    }

    extension Order where T: Cancellable {
    var cancel: Order<Cancelled> {
    return Order<Cancelled>()
    }
    }

    extension Order where T: Billable {
    var bill: Order<Billed> {
    return Order<Billed>()
    }
    }

    extension Order where T == Billed {
    var pack: Order<Packed> {
    return Order<Packed>()
    }
    }

    extension Order where T == Packed {
    var ship: Order<Shipped> {
    return Order<Shipped>()
    }
    }

    let o1 = Order<Initial>()
    let o2 = o1.place.bill.pack.ship
    print(o2)