title: Bad dispatch group Notify placement?
body: <p>I'm using a Dispatch Group to call a function once all values in my dictionary have been iterated through. At the start of each item's block I call <code>enter()</code> then call <code>leave()</code> at the end. I'm putting the dispatch group's <code>notify</code> callback at the end of each item's code block, but I'm wondering if this actually makes the callback be called each time an item finishes instead of after all the items have finished. Here's what I have:</p>
  
  <pre><code>for value in snap {
      self.dispatchGroup.enter()
      let petName = value.key as! String
      self.petsDict[petName] = UIImage()
  
      // Check if pet's image is cached, otherwise fetch from db
      if let petImg = petName.pngImageInDocumentsFolder() {   // Image is cached
          print("Image is cached \(petName)")
          self.petsDict[petName] = petImg
          self.dispatchGroup.leave()
      } else {                                                // Image not cached, fetch it
          let imgRef = FIRStorage.storage().reference().child("profile_images").child(petName+".png")
          imgRef.data(withMaxSize: 1 * 1024 * 1024) { (data, error) -&gt; Void in
              if error != nil {
                  print(error?.localizedDescription ?? "")
                  self.dispatchGroup.leave()
              } else if let data = data, let image = UIImage(data: data){
                  self.petsDict[petName] = image
                  self.dispatchGroup.leave()
              }
  
          }
      }
      self.dispatchGroup.notify(queue: DispatchQueue.main, execute: {
          self.loadScrollView()
      })
  }
  </code></pre>
  
  <p>Since some of these items would perform synchronously (if their image is cached) I think that the next item's loop wouldn't even start by the time the dispatch group's <code>leave()</code> is called, and therefore the <code>notify</code> would be called.</p>
  
  <p>Should I instead be putting a separate <code>enter()</code> before this for loop starts, then a final <code>leave()</code> after all the items loops have at least started, so that their <code>enters()</code> are accounted for? </p>
  
  <p><strong>Edit:</strong> I put a print statement in my callback function and confirmed its being called more than once. I guess I'll go with my solution above unless someone has a better one.</p>