Created
July 31, 2014 08:40
-
-
Save westerlund/38737e67e7f7287ec322 to your computer and use it in GitHub Desktop.
Waiting in Swift
This file contains 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
// github doesn't support .playground files, just copy this in a playground to quick run it | |
class AsyncThing { | |
// set up a optional callback variable that takes a closure with a return of Void | |
// that closure takes another (non-optional) closure named "done" which returns Void | |
var callback:((done: () -> Void) -> Void)? | |
// just a dummy method to execute the blocks | |
func run() { | |
// set up a constant block, this is just for readability | |
// it returns Void. this is the inner closure. | |
let doneClosure: () -> Void = { | |
println("done was called") | |
} | |
// call our callback with our closure in it | |
callback!(doneClosure) | |
} | |
} | |
let t = AsyncThing() | |
// setup callback, it takes a closure as argument | |
t.callback = { | |
done in // extract the closure, this can also be typed as "done: () -> Void in". | |
// try alt-click on this and see what the compiler gives you! | |
println("executing something") // run some dummy code | |
done() // call our block when finished | |
} | |
// run the method that executes the blocks | |
t.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment