ios - 变量在不应该上升的时候上升

标签 ios swift

我有一个应用程序,按下按钮会使分数增加 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/

相关文章:

ios - 下载图像,然后从 Firebase Swift 3 缓存它

ios - Facebook SSO IOS 不返回app

iOS如何让uiview知道出现和消失?

ios - 通用链接 IOS9

ios - 在 ScrollView 中放置了一个 TableView ,现在我无法使用滑动来删除

ios - 当标题位于 View 顶部时取消分组 UITableView 部分标题

ios - NSPredicate 和 BEGINSWITH 与 CloudKit : Field value type mismatch

iphone - XMPP 框架接收的最大消息数

swift 3 : AppDelegate does not conform to protocol GIDSignInDelegate

ios - 文件更改时 Xcode 停止读取文本文件