Skip to content

Instantly share code, notes, and snippets.

@gregomni
Created March 21, 2018 04:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gregomni/715a0727c9990b15356d3fa987624151 to your computer and use it in GitHub Desktop.
Save gregomni/715a0727c9990b15356d3fa987624151 to your computer and use it in GitHub Desktop.
public protocol Thing {
associatedtype T
func work() throws -> T
}
public struct AnyThing<T> : Thing {
let doWork: () throws -> T
public func work() throws -> T {
return try doWork()
}
}
public struct CompositeThing<T> : Thing {
public enum Error : Swift.Error {
case noap
}
public func work() throws -> T {
for thing in things {
do {
return try thing.work()
} catch {
}
}
throw CompositeThing.Error.noap
}
public var things: [AnyThing<T>] = []
public mutating func addThing<U : Thing>(_ thing: U) where U.T == T {
things.append(AnyThing(doWork: thing.work))
}
}
public struct ThingOne<T> : Thing {
public func work() -> T {
fatalError("one")
}
}
public struct ThingTwo<T> : Thing {
public func work() -> T {
fatalError("two")
}
}
var composite = CompositeThing<Int>()
composite.addThing(ThingOne())
composite.addThing(ThingTwo())
_ = try composite.work()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment