变量在不应该的时候上升

时间:2017-06-10 15:28:32

标签: ios swift

我有这个应用程序按下一个按钮使得得分上升一,直到你达到50以上,然后按下按钮将2添加到得分。但问题是,每按一次按钮都会将级别改为1。这是我的代码:

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

1 个答案:

答案 0 :(得分:0)

看起来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
    }
}