Skip to content

Instantly share code, notes, and snippets.

@apinstein
Created December 25, 2014 05:31
Show Gist options
  • Save apinstein/6d69438df97f50e37cfa to your computer and use it in GitHub Desktop.
Save apinstein/6d69438df97f50e37cfa to your computer and use it in GitHub Desktop.
Swift Promise example
// Example of a promise that could be used to wrap bracketed capture
import Foundation
import BrightFutures
func grabBrackets (n:Int) -> Future<[AnyObject]> {
let promise = Promise<[AnyObject]>()
var data = [AnyObject]()
let allDoneCheck = { () -> Void in
if data.count == n {
promise.success(data)
}
}
// simulate return of N items
Queue.global.async {
//NSThread.sleepForTimeInterval(1.0)
data.append(1)
allDoneCheck()
Queue.global.async {
//NSThread.sleepForTimeInterval(1.0)
data.append(2)
allDoneCheck()
}
}
return promise.future
}
// goes unfulfilled
let f3 = grabBrackets(3)
f3.value
// gets fulfilled
let f2 = grabBrackets(2)
f2.value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment