首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我的变量不会超过8

我的变量不会超过8
EN

Stack Overflow用户
提问于 2017-06-09 17:46:35
回答 4查看 69关注 0票数 0

我有一个有一个按钮的应用程序,每次你按下它,变量就会被1加进去。然后由变量设置一个标签。但是当标签达到8,然后再按下按钮,它就会用fatal error: Index out of range崩溃。

这是我的密码:

代码语言:javascript
复制
import UIKit

class ViewController: UIViewController {

// OUTLETS

@IBOutlet weak var score: UILabel!
@IBAction func add(_ sender: Any) {
    add()
}


// VARIABLES

var scoreVar = 0
let levelUpAt = [50, 100, 500, 1000, 5000, 10000, 50000, 100000]
var currentLevel = 1
var toAdd = 1

// OVERRIDES

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// FUNCTIONS

// Below code adds to the score

func add() {
    scoreVar += 1 // Adds 1 to scoreVar
    score.text = "\(scoreVar)"; // Updates text to match
    checkForLevelUp(); // Calls the function defined in the next few days ago
}

// Below code checks if the score meets the next level requirements

func checkForLevelUp() {
    if (scoreVar - 1 < levelUpAt[currentLevel - 1]) { // Complicated math-y if statment
        currentLevel += 1
        toAdd += 1
    }
}
}
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2017-06-09 17:51:17

这是因为变量为8,数组的最后一个索引为7,这是获得fatal error: Index out of range的方法。

你的if-statement是这样的吗?

代码语言:javascript
复制
if (scoreVar - 1 < levelUpAt[currentLevel - 1] && levelUpAt.indices.contains(currentLevel)) { ... }

因此,基本上检查数组中是否也存在该索引:

代码语言:javascript
复制
levelUpAt.indices.contains(currentLevel)
票数 0
EN

Stack Overflow用户

发布于 2017-06-09 17:51:59

这里:if levelUpAt[currentLevel - 1],您正在访问一个数组元素。数组中只有8个元素。一旦currentLevel达到8,它将访问数组不包含的元素,因此会崩溃。

票数 3
EN

Stack Overflow用户

发布于 2017-06-09 17:51:37

数组中只有8个元素。

代码语言:javascript
复制
let levelUpAt = [50, 100, 500, 1000, 5000, 10000, 50000, 100000]

currentLevel = 9和你给checkForLevelUp()打电话,现在它已经超出了范围。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44463917

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档