我有一个应用程序,按下按钮会使分数增加 1,直到分数超过 50,然后按下按钮将分数加 2。但问题是,每按一次按钮都会使级别改变一级。这是我的代码:
import UIKit
class ViewController: UIViewController {
// OUTLETS
@IBOutlet weak var score: UILabel!
@IBOutlet weak var levelLabel: UILabel!
@IBAction func add(_ sender: Any) {
add()
}
// VARIABLES
var scoreVar = 0
let levelUpAt = [10, 50, 100, 500, 1000, 5000, 10000, 50000, 100000]
var currentLevel = 1
var toAdd = 1
// FUNCTIONS
// Below code adds to the score
func add() {
if (scoreVar - 1 < levelUpAt[currentLevel - 1] && levelUpAt.indices.contains(currentLevel)) { // Complicated math-y if statment THANK YOU RASHWAN L (STACK OVERFLOW) FOR HELPING
currentLevel += 1 // Change level
toAdd += 1 // Change toAdd
levelLabel.text = "Level \(currentLevel)" // Change the level label
scoreVar += toAdd // Adds toAdd (level amount) to scoreVar
score.text = "\(scoreVar)"; // Updates text to match
} else {
scoreVar += toAdd // Adds toAdd (level amount) to scoreVar
score.text = "\(scoreVar)"; // Updates text to match
}
}
}
最佳答案
看起来 if
条件应该运行 else
代码,反之亦然。第一个要比较的值是 scoreVar
而不是 scoreVar - 1
。
func add() {
if (scoreVar < levelUpAt[currentLevel - 1] && levelUpAt.indices.contains(currentLevel)) { // Complicated math-y if statment THANK YOU RASHWAN L (STACK OVERFLOW) FOR HELPING
scoreVar += toAdd // Adds toAdd (level amount) to scoreVar
score.text = "\(scoreVar)"; // Updates text to match
} else {
currentLevel += 1 // Change level
toAdd += 1 // Change toAdd
levelLabel.text = "Level \(currentLevel)" // Change the level label
scoreVar += toAdd // Adds toAdd (level amount) to scoreVar
score.text = "\(scoreVar)"; // Updates text to match
}
}
关于ios - 变量在不应该上升的时候上升,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44475029/