Created
April 20, 2016 21:05
-
-
Save algal/b5d459105c19eecf6adeab91c9eb6bfc to your computer and use it in GitHub Desktop.
Experiment with generic NSOperation composition
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol FunctionOperation : class { | |
associatedtype InputType | |
associatedtype OutputType | |
var input:InputType? { get set } | |
var output:OutputType? { get set } | |
func addDependency(op: NSOperation) | |
} | |
/** | |
Returns an _adapter block_ which passes the output from `f` into the input of `g`, and builds dependencies so f runs first, then the adapter, then g. | |
The client is still responsible for adding all three blocks to queues. | |
*/ | |
func adapterOperationToChainOperations<F:FunctionOperation,G:FunctionOperation | |
where F.OutputType == G.InputType>(f:F,g:G) -> NSBlockOperation | |
{ | |
guard let fop = f as? NSOperation else { fatalError() } | |
guard let gop = g as? NSOperation else { fatalError() } | |
let adapterOp = NSBlockOperation { | |
g.input = f.output | |
} | |
adapterOp.addDependency(fop) | |
gop.addDependency(adapterOp) | |
return adapterOp | |
} | |
/** | |
Encapsulates a single closure evaluation | |
*/ | |
class FunctionBlockOperation<InputType,OutputType> : NSOperation, FunctionOperation | |
{ | |
let fn:(InputType) -> OutputType | |
var input:InputType? | |
var output:OutputType? | |
init(block:(InputType)->OutputType) { | |
self.fn = block | |
} | |
override func main() { | |
self.output = self.fn(self.input!) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment