jeudi 7 novembre 2019

How to you end an if-else loop without the program crashing?

I am creating an app in xcode where the user is asked a series of questions and they input an answer. (Don't worry, my question isn't xcode related) The questions and answers are both stored in arrays, and I have an if-else statement that prints out the question and recognizes the answer. I only have 5 questions in the array. Once the user submits the answer to question 5, the app crashes and an error stating "Thread 1: Fatal error: Index out of range" appears. How to I get the if-else statement to recognize that it has run out of questions in the array and get the program to move on to other lines of code?

I have already tried a series of different types of loops, like while, repeat, switch statements, and for loops. None of them are as successful as the if-else statement (meaning they crash sooner that the if-else does). I've also tried creating a if-else inside of the original statement. For example, I tried: if (x >= 6){ return } However, I still receive the same "Index out of range" error.

let question = ["What is the number 1?", "What is the number 2?", 
"What is the number 3?", "What is the number 4?", "What is the 
number 5?"]
    let answer = ["1", "2", "3", "4", "5"]

    var x = 0

@IBAction func submissionButton(_ sender: Any) { 
      if answerBox.text! == answer[x]
            {
                x += 1
                print("correct")
                question.text = question[x]
                answerBox.text = ""

            }
       else if (x >= 6)
       {
            print("done")
            return
       {
       else
            {
                print("wrong")
                answerBox.text = ""
            }
}

Whenever I run the program and enter the questions, the app crashes after I answer "What is question 5?" and I get the error "Thread 1: Fatal error: Index out of range" . However, I wanted the terminal to print "done".

Aucun commentaire:

Enregistrer un commentaire