0

Im making a Quiz game with swift and I have run into an issue. My RandomQuestionGenerator function doesn't seem to be changing my correctAnswer variable. I tested this by changing the if correctAnswer == 1 to if correctAnswer == 0 and the code when I press the button runs. Im guessing there is a stupid obvious solution but I can't figure it out.

var correctAnswer = 0 
func RandomQuestionGenerator(){

    var randomQuestion = 
    Int(arc4random_uniform(UInt32(fullQuestions.count)))
    var currentQuestion = fullQuestions[randomQuestion]
    var correctAnswer = currentQuestion.answer

    Label.text = currentQuestion.Question
    Button1.setTitle(currentQuestion.answers[0], for: .normal)
    Button2.setTitle(currentQuestion.answers[1], for: .normal)
    Button3.setTitle(currentQuestion.answers[2], for: .normal)
    Button4.setTitle(currentQuestion.answers[3], for: .normal)

    fullQuestions.remove(at: randomQuestion)
}

override func viewDidAppear(_ animated: Bool) {
    appendQuestions()
    RandomQuestionGenerator()

}

@IBAction func Button1Pressed(_ sender: Any) {
    if correctAnswer == 1{
        RandomQuestionGenerator()
    }
}
1
  • The line var currentQuestion = fullQuestions[randomQuestion] is not a simple assignment. It's a variable declaration in the local code-block. Newly declared variable shadows the same names in the outer scope. Just remove var in that line. You should always distinguish variable declarations and assignments. Commented Aug 14, 2017 at 0:16

1 Answer 1

1

As OOPer said, the line var currentQuestion = fullQuestions[randomQuestion] does not reassign the variable, it "shadows" the global variable. This means that in the scope of the function, it is as if you have a separate variable with the same name. When you exit the function, the variable reverts to the value you declared in the beginning. To reassign the variable, use currentQuestion = fullQuestions[randomQuestions], as that will not shadow, but simply reassign the variable

However, this may not be your problem. I noticed that in your currentQuestion.answers array, you have four values, with the indices 0,1,2, and 3. However, you named your buttons 1,2,3 and 4. It looks like this is why your if statement is if correctAnswer == 1. If the first answer is the correct one in this case, and currentQuestion.answer can either be 1,2,3 or 4, that may be your problem. If this is your problem, it can be fixed by replacing the if statements with if correctAnswer = 0 for button1' correctAnswer = 1 for button2, and so on

Hope this helps!

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, I knew it would be a stupid easy solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.