title: for loop with async closure
body: <p>I am trying to pass some array through segue but before that I have to run simple for loop but I have a problem. For each iteration I need so perform a function with networking and async. After complete, it has to append String to array and after for loop ends, pass the data on segue.</p>
  
  <p>I have a problem because when try this, I get crash for data not being passed and is nil on new controller. I am assuming, I need to use GCD or something similar to inform when all is complete and that pass data.</p>
  
  <p>What I tried first:</p>
  
  <pre><code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  
  selectedStory = stories[indexPath.row]
  
  for chapter in (selectedStory?.chapters)! {
    DataService.instance.retrieveUsername(forID: chapter.author) { (returnedUsernamed) in
      self.selectedStoryChapterAuthors?.append(returnedUsernamed)
  
    }
  }
  
  self.performSegue(withIdentifier: "goToStory", sender: self)}
  </code></pre>
  
  <p>How I tried to make this work with DispatchGroup but didn't work:</p>
  
  <pre><code>let dispatchGroup = DispatchGroup()
  
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  
  selectedStory = stories[indexPath.row]
  
  for chapter in (selectedStory?.chapters)! {
    dispatchGroup.enter()  //  Enter the dispatch group
    DataService.instance.retrieveUsername(forID: chapter.author) { (returnedUsernamed) in
      self.selectedStoryChapterAuthors?.append(returnedUsernamed)
  
      self.dispatchGroup.leave()
    }
  }
  
  dispatchGroup.notify(queue: DispatchQueue.main, execute: {
    self.performSegue(withIdentifier: "goToStory", sender: self)
  }) }
  </code></pre>
  
  <p>Any idea on this? If more info/code needed, lemme know.</p>