Skip to content

Instantly share code, notes, and snippets.

@jayrhynas
Created January 26, 2017 16:59
Show Gist options
  • Select an option

  • Save jayrhynas/530d114d608f0d9ee1e3e09a04368dc4 to your computer and use it in GitHub Desktop.

Select an option

Save jayrhynas/530d114d608f0d9ee1e3e09a04368dc4 to your computer and use it in GitHub Desktop.
import Foundation
func asyncFor<T>(_ initial: T, _ condition: @escaping (T) -> Bool, _ update: @escaping (T) -> T, _ body: @escaping (T, @escaping () -> Void) -> Void, _ done: @escaping () -> Void) {
var state = initial
var next: (() -> Void)!
next = {
body(state, {
state = update(state)
if condition(state) { next() }
else { done() }
})
}
next()
}
asyncFor(0, { $0 < 10 }, { $0 + 1 }, { i, next in
DispatchQueue.main.async {
print(i)
next()
}
}, {
print("done")
exit(0)
})
RunLoop.current.run()
@jayrhynas
Copy link
Author

Output:

0
1
2
3
4
5
6
7
8
9
done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment