title: How to Delay a For Loop Until Sound has Finished Playing in Swift
body: <p>So, I have a for loop that runs values from an array into an if statement. The if statement plays a sound depending on the value in the array.</p>
  
  <p>However, right now, all the values are being run through at once, so the sounds are all played at the same time. Here's what my code looks like right now:</p>
  
  <pre><code>// sortedKeys is an array made from the keys in the newData dictionary.
  let sortedKeys = Array(newData.keys).sort(&lt;)
  
  // newData is the dictionary of type [float:float] being used to get the values that are then being run through the if statement.
      for (value) in sortedKeys {
          let data = newData[value]
          if data &lt;= Float(1) {
              self.audioPlayer1.play()
          } else if data &lt;= Float(2) &amp;&amp; data &gt; Float(1) {
              self.audioPlayer2.play()
          } else if data &lt;= Float(3) &amp;&amp; data &gt; Float(2) {
              self.audioPlayer3.play()
          } else if data &lt;= Float(4) &amp;&amp; data &gt; Float(3) {
              self.audioPlayer4.play()
          } else if data &lt;= Float(5) &amp;&amp; data &gt; Float(4) {
              self.audioPlayer5.play()
          } else if data &lt;= Float(6) &amp;&amp; data &gt; Float(5) {
              self.audioPlayer6.play()
          } else if data &lt;= Float(7) &amp;&amp; data &gt; Float(6) {
              self.audioPlayer7.play()
          } else if data &lt;= Float(8) &amp;&amp; data &gt; Float(7) {
              self.audioPlayer8.play()
          } else if data &lt;= Float(9) &amp;&amp; data &gt; Float(8) {
              self.audioPlayer9.play()
          } else {
              self.audioPlayer10.play()
          }
      }
  </code></pre>
  
  <p>How can I make it so that once the <code>AVAudioPlayer</code> finishes playing, I continue the for loop to get the next sound? I'm thinking it has something to do with <code>AVPlayerItemDidPlayToEndTimeNotification</code>, but I don't know how to use this to delay the for loop.</p>
  
  <p>Thanks!</p>