You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Swift开发问题:答对题目分数应加1却加2,求排查解决

Fix: Score Doubles on Correct Answer in Swift Quiz App

Hey there! Let's break down why your score is jumping by 2 instead of 1 when you get a question right—it's a simple, easy-to-miss issue with how you're using your checkAnswer method.

The Root Cause

Take a look at this part of your answerButtonPressed code:

let userGotItRight = quizBrain.checkAnswer(userAnswer)
print(quizBrain.checkAnswer(userAnswer))

You’re calling quizBrain.checkAnswer(userAnswer) twice here! Since checkAnswer is a mutating function that adds 1 to your score every time the answer is correct, each call triggers that score increment. That’s why you’re seeing +2 instead of +1 for correct answers.

The Fix

Just call checkAnswer once, save its result to a variable, and reuse that variable for both your logic check and the print statement:

@IBAction func answerButtonPressed(_ sender: UIButton) {
    let userAnswer = sender.currentTitle!
    // Only call checkAnswer ONCE and store the result
    let userGotItRight = quizBrain.checkAnswer(userAnswer)
    print(userGotItRight) // Use the stored result instead of re-calling the method
    
    if userGotItRight{
        UIView.animate(withDuration: 0.2) {
            sender.backgroundColor = #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1)
        }
        UIView.animate(withDuration: 0.2) {
            sender.backgroundColor = UIColor.clear
        }
    }else{
        UIView.animate(withDuration: 0.2) {
            sender.backgroundColor = #colorLiteral(red: 0.9098039269, green: 0.4784313738, blue: 0.6431372762, alpha: 1)
        }
        UIView.animate(withDuration: 0.2) {
            sender.backgroundColor = UIColor.clear
        }
    }
    quizBrain.nextQuestion()
    updatedUI()
}

Why This Works

Mutating methods like checkAnswer modify your struct’s internal state (in this case, the score variable) every time they run. By saving the result to userGotItRight first, you avoid triggering that score increment a second time when you print the result. This keeps your score logic consistent with what you expect.

内容的提问来源于stack exchange,提问作者tashaxing

火山引擎 最新活动