skip to Main Content

I am creating a quiz app as a school project, but when I am creating the questions there was a problem that occurred. The quiz itself works, but as soon as I added constraints to the buttons on the storyboard, there some issues which occurred, and I want to know if I can get some help? The code is as follows, and is in the language of swift:


class MathsViewController: UIViewController {
    

    let questions = ["What is the turning point of the graph, y = x^2 + 8x + 6 ?", "What are the x-intercepts of the graph, y = x^2 + 11x + 18 ?", "What is the triganomic ratio used when relating the opposite and adjacent?", "What would be the final form of the equation, 14/x = sin(20) ?", "Which equation, would have the steepest slope?", "If we added every positive whole number, what would the solution be?", "Which of the following is the fibonacci sequnce?", "What are the first 10 digits of pi?", "What is the probability of getting a 6 in all your rolls, when rolling a dice 3 times?", "If the hypostenuse of a triangle is 26cm, and a side edge is of 10cm long. What is the length of the other side?"]
    

    let answers = [["(-4, -10)", "(0,0)", "(-6, -1)"], ["x = -2 or x = -9", "x = 18 or x = 11", "x = 9 or x = 2"], ["tan", "cos", "sin"], ["x = 14/sin(20)", "x = 14sin^-1/20", "x = sin^-1(20)"], ["y = 5x+2", "y = 1/3x+4", "y = x+16"], ["-1/12", "infinity", "0"], ["1,1,2,3,5,8,13", "1,2,3,4,5,6,7", "1,1,2,2,4,8,32"], ["3.1415926535", "3.141533536", "3.1415934435"], ["1/216", "1/36", "1/6"], ["24cm", "28cm", "26cm"]]
    

    //Variables
    var currentQuestion = 0
    var rightAnswerPlacement = 0
    var points = 0;
    

    //Label
    @IBOutlet weak var Label: UILabel!
    

    //Button
    @IBAction func action(_ sender: Any)
    {
        if (sender as AnyObject).tag == Int(rightAnswerPlacement)
        {
            print("RIGHT!")
            points += 1
        }
        else
        {
            print("WRONG!!!")
        }
        

        if (currentQuestion != questions.count)
        {
            newQuestion()
        }
        else
        {
            performSegue(withIdentifier: "showScore", sender: self)
        }
        print(points)
    }
    

    

    override func viewDidLayoutSubviews() {
        newQuestion()
    }
    

    //Function that displays new question
    func newQuestion()
    {
        Label.text = questions[currentQuestion]
        

        rightAnswerPlacement = Int(arc4random_uniform(3)+1)
        

        //Create Button
        var button:UIButton = UIButton()
        

        var x = 1
        

        for i in 1...3
        {
            //Create a button
            button = view.viewWithTag(i) as! UIButton
            

            if (i == Int(rightAnswerPlacement))
            {
                button.setTitle(answers[currentQuestion][0], for: .normal)
            }
            else
            {
                button.setTitle(answers[currentQuestion][x], for: .normal)
                x = 2
            }
        }
        currentQuestion += 1
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    


}

Here are some images of the error message:

The code with the error message

Error Message in the debug area

Furthermore, here are some images of my storyboard to help you visualise:

Quiz interface

Final Screen

The final screen is blank with a single label, this is the screen which comes up after the quiz is complete, I need to code it so the score will replace the label.

Any help is appreciated.

Thank you in advance!

3

Answers


  1. Your crash occurs because you are trying to index past the length of your questions array, not because of constraint violations.

    Login or Signup to reply.
  2. Index out of range means that you have n elements in an array but you tried to reach the n+1 which doesn’t exist. So I’m assuming the problem lays in currentQuestion‘s index.
    If you use array you need to keep in mind that indices in array starts from 0 and ends at n-1, so if you have 3 elements in your questions array, you can access them like questions[0], questions[1], questions[2]. But if you try to access questions[3] you will get such type of error.

    Login or Signup to reply.
  3. First understand that this is not a constraint error.

    This is an exception caused at run time of your app(run time error).

    Suppose, you have 10 questions in your "questions" array. You’re checking for condition:-

        if (currentQuestion != questions.count)
        {
            newQuestion()
        }
        else
        {
            performSegue(withIdentifier: "showScore", sender: self)
        }
    

    Here the the iteration will be followed for about 0 to 10th position because the array count you’re getting will be 11. But in this case you’ll be having no element in the 10th position of your "question" array. So, you have to put condition like this

        if (currentQuestion != (questions.count - 1))
        {
            newQuestion()
        }
        else
        {
            performSegue(withIdentifier: "showScore", sender: self)
        }
    

    This will iterate from 0 to 9th position which is your 10th question in the array.
    Please understand what @MohyG is trying to explain you & then proceed with this code.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search