Richard Parker
Richard Parker

Reputation: 65

Function not changing variable (Swift)

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()
    }
}

Upvotes: 0

Views: 54

Answers (1)

Sam
Sam

Reputation: 2446

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!

Upvotes: 1

Related Questions