title: Auto play audio files in Swift
body: <p>I'm making a very simple app in which the user get to select some audio files he wants to play. 
  Then, he pushes the Play button and, it would play all the files selected one after another. </p>
  
  <p>To do so, I made an array that stores the name of the files the users wants to play. Then, a function triggered by the Play button would make a iteration of the array, look for the names and play the files. </p>
  
  <p>It's something like this :</p>
  
  <pre><code>//declaring the audioplayer
  var audioPlayer = AVAudioPlayer()
  
  //declaring the array
  var selectedMusic = [String]()
  </code></pre>
  
  <p>The interface got 6 buttons, one of each is linked to a specific music. The user can trigger the music instantly by tapping the button, or make a selection for a sequential play by a long press. Let's assume that the user got a selection and the array would look something like this : </p>
  
  <pre><code>selectedMusic = ["Song 1", "Song 5", "Song 3", "Song 2"]
  </code></pre>
  
  <p>My function to play the songs is : </p>
  
  <pre><code>for selection in selectedMusic {
  
          if selection == "Song 1" {
  
              guard let alertSound = Bundle.main.url(forResource: "Song 1", withExtension: "mp3") else {return}
  
              do {
                  try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
                  try AVAudioSession.sharedInstance().setActive(true)
  
  
                  audioPlayer = try AVAudioPlayer(contentsOf: alertSound)
                  audioPlayer.prepareToPlay()
                  audioPlayer.play()
  
              } catch let error {
                  print(error.localizedDescription)
              }
  
          } else if selection == "Song 2" {
  
              guard let alertSound = Bundle.main.url(forResource: "Song 2", withExtension: "mp3") else {return}
  
              do {
                  try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
                  try AVAudioSession.sharedInstance().setActive(true)
  
  
                  audioPlayer = try AVAudioPlayer(contentsOf: alertSound)
                  audioPlayer.prepareToPlay()
                  audioPlayer.play()
  
              } catch let error {
                  print(error.localizedDescription)
              }
  </code></pre>
  
  <p>Etc, until Song 5. </p>
  
  <p>What I want is to play the selected songs in a specific order (1 to 5) and not the order the user chose (it's important). </p>
  
  <p>Yet, this function is not giving the expected results, it's just playing the last item of the selection. </p>
  
  <p>So, how should I make this work ? Is the array not the best option here ? 
  As i mentioned, the fact that the songs are played in chronological order is mandatory. </p>
  
  <p>Any help would be greatly appreciated :)
  Thanks !</p>