title: Passing and storing closures/callbacks in Swift
body: <p>I would like to do the following in swift code:</p>
  
  <p>I have to call my api in order to update several items. So I call the api for each item asynchronously. Each api call executes a callback function when it's done. These callbacks decrease a counter, so that when the counter reaches 0 I know that all my api calls are completed. When the counter reaches 0 I would like to call a final callback function (once, when all calls are complete), in order to update my UI and so forth. This final callback is passes to my service in the beginning and stored in a class property for later execution.</p>
  
  <p>Executable Playground source:</p>
  
  <pre><code>// Playground - noun: a place where people can play
  
  class MyService
  {
      let api = MyApi()
  
      var storedFinalCallback: () -&gt; Void = { arg in }
      var queue: Int                      = 0
  
      func update(items: [String], finalCallback: () -&gt; 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: {() -&gt; Void in
      println("Done")
  })
  </code></pre>
  
  <p>The problem is that with this code the final callback is called in the wrong order. <img src="https://i.stack.imgur.com/B3c5L.png" alt="As the console output from the playground shows."></p>
  
  <p>Apparently the callback function is already executed and not properly passed. However, this was the only way I was able to do it, without compiler errors.</p>
  
  <p>Any help would be really appreciated - I have been stuck on this for two days now.</p>