我有一个有一个按钮的应用程序,每次你按下它,变量就会被1加进去。然后由变量设置一个标签。但是当标签达到8,然后再按下按钮,它就会用fatal error: Index out of range崩溃。
这是我的密码:
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
}
}
}发布于 2017-06-09 17:51:17
这是因为变量为8,数组的最后一个索引为7,这是获得fatal error: Index out of range的方法。
你的if-statement是这样的吗?
if (scoreVar - 1 < levelUpAt[currentLevel - 1] && levelUpAt.indices.contains(currentLevel)) { ... }因此,基本上检查数组中是否也存在该索引:
levelUpAt.indices.contains(currentLevel)发布于 2017-06-09 17:51:59
这里:if levelUpAt[currentLevel - 1],您正在访问一个数组元素。数组中只有8个元素。一旦currentLevel达到8,它将访问数组不包含的元素,因此会崩溃。
发布于 2017-06-09 17:51:37
数组中只有8个元素。
let levelUpAt = [50, 100, 500, 1000, 5000, 10000, 50000, 100000]currentLevel = 9和你给checkForLevelUp()打电话,现在它已经超出了范围。
https://stackoverflow.com/questions/44463917
复制相似问题