I want to do the following in quick code:
I need to call api to update multiple items. Therefore, I call api for each element asynchronously. Each api call performs a callback function when this is done. These callbacks decrease the counter, so when the counter reaches 0, I know that all my api calls have completed. When the counter reaches 0, I would like to call the callback function (once when all the calls are completed) to update my interface, etc. This last callback goes to my service at the beginning and is stored in the class property for later execution.
Playground source:
// Playground - noun: a place where people can play class MyService { let api = MyApi() var storedFinalCallback: () -> Void = { arg in } var queue: Int = 0 func update(items: [String], finalCallback: () -> Void ) { // Count the necessary API calls queue = items.count // Store callback for later execution storedFinalCallback = finalCallback for item in items { // Call api per item and pass queueCounter as async callback api.updateCall(item, callback: self.callback()) } } func callback() { queue-- // Execute final callback when queue is empty if queue == 0 { println("Executing final callback") storedFinalCallback() } } } class MyApi { func updateCall(item: String, callback: ()) { println("Updating \(item)") } } let myItems: [String] = ["Item1", "Item2", "Item3"] let myInstance: MyService = MyService() myInstance.update(myItems, finalCallback: {() -> Void in println("Done") })
The problem is that with this code, the final callback is called in the wrong order. 
Apparently, the callback function has already been completed and is incorrectly passed. However, this was the only way I was able to do this, without compiler errors.
Any help would be greatly appreciated - I've been stuck on it for two days now.
source share