Swift var得分不会增加

  • 本文关键字:增加 var Swift swift var
  • 更新时间 :
  • 英文 :

var players : [Player]?
var currentplayerIndex = 0
var currentQuestion : QuestionObject!
var questions = Questions()
var score = 0
var currentQuestionPos = 0

func updateUi() {
if let score = players?[currentplayerIndex].score {
playerPoints.text = "Points: (score)"
}
}
func loadnextQuestion () {
if(currentQuestionPos < questions.questions.count) {
currentQuestionPos += 1
if currentplayerIndex < players!.count - 1 {
currentplayerIndex += 1
} else {
currentplayerIndex = 0
}
playerTurn.text = (players?[currentplayerIndex].name)
currentQuestion = questions.questions[currentQuestionPos]
questionText.text = currentQuestion.question
}
}

@IBAction func submitButtonPressed(_ sender: UIButton) {
let i = pickerView.selectedRow(inComponent: 0)
if(currentQuestion.answer == i) {
players?[currentplayerIndex].score += 1
loadnextQuestion()
updateUi()
} else {
updateUi()
loadnextQuestion()
}
}

}

我的分数一直只显示0。答案正确时不会增加。所有添加的玩家每人得到1个问题,但所有玩家的问题仍然为0。

您的代码不起作用,因为当答案正确时,您正在执行以下一系列操作:

players?[currentplayerIndex].score += 1
loadnextQuestion()
updateUi()

玩家的分数实际上是递增的。但请注意,接下来要做的是loadnextQuestion(),它会使currentplayerIndex递增。这导致updateUi将标签的文本更新为下一个玩家的分数,而不是刚刚正确回答问题的玩家的分数。

解决这个问题的一种方法是交换最后两行:

players?[currentplayerIndex].score += 1
updateUi()
loadnextQuestion()

请注意,这与您正确编写的else分支中的顺序相同。

这导致标签总是显示最后一个玩家的分数,这可能是不可取的。假设没有100名玩家或类似疯狂的东西,我认为如果你显示所有玩家的分数,这将是一个更好的用户体验:

func updateUi() {
if let scores = players?.map({ "($0.score)" }) {
playerPoints.text = "Points: (scores.joined(separator: ", "))"
}
}

您可以替换按钮动作工作

@IBAction func submitButtonPressed(_ sender: UIButton) {
let i = pickerView.selectedRow(inComponent: 0)
if(currentQuestion.answer == i) {
players?[currentplayerIndex].score += 1
updateUi()
loadnextQuestion()
} else {
updateUi()
loadnextQuestion()
}
}

最新更新