title: How to loop through JSON objects in Swift?
body: <p>I'm new to Swift and I can't figure this out. I'm creating a simple quiz app where the questions are coming from a json file. I am able to successfully parse this data but I can't figure out how to loop through the json file to show each question. Currently, only the first question is being displayed and when an answer is selected, it shows the answer as correct/incorrect and nothing else. I would like for the next question to be populated from the json file once a user answers a question but I can't figure out how to do that. This is the code I have so far.</p>
  
  <pre><code>private func parseJSON() {
      guard let path = Bundle.main.path(forResource: "quizQuestions", ofType: "txt") else { return }
      let url = URL(fileURLWithPath: path)
  
      do {
          let data = try Data(contentsOf: url)
          let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
  
          guard let array = json as? [Any] else { return }
  
          for item in array {
              guard let quizObjects = item as? [String: Any] else { return }
              guard let questionNumber = quizObjects["id"] as? Int else { print("not an Int"); return }
              guard let question = quizObjects["question"] as? String else { return }
              guard let answerChoices = quizObjects["answerChoices"] as? [String] else { return }
              guard let correctAnswer = quizObjects["correctAnswer"] as? Int else { return }
          }
      }
      catch {
          print(error)
      }
  }
  </code></pre>
  
  <p>I have included the loadNextQuestion function for you to see what I'm trying to do. Previously, I had all of the questions hard-coded in a swift object so this worked but now I am trying to pull from a json file. The main thing I'm struggling with is how to determine the current question and position in order to make this logic work.</p>
  
  <pre><code>func loadNextQuestion() {
      // Show next question
      if(currentQuestionPos + 1 &lt; currentQuestion.count) {
          currentQuestionPos += 1
          currentQuestion = question
          setQuestion()
  
      }
      // If there are no more questions show the results
      else {
  
      }
  }
  </code></pre>
  
  <p>Here is the json file I'm pulling from:</p>
  
  <pre>
  [
  {
  "id": 1,
  "question": "What color is the sky?",
  "answerChoices": ["Green", "White", "Blue", "Brown"],
  "correctAnswer": 2
  },
  
  {
  "id": 2,
  "question": "What color is the grass?",
  "answerChoices": ["Pink", "Green", "Purple", "Orange"],
  "correctAnswer": 0
  },
  
  {
  "id": 3,
  "question": "Which of these has 8 legs?",
  "answerChoices": ["Spider", "Lizard", "Cricket", "Snake"],
  "correctAnswer": 0
  },
  ]
  </pre>