【发布时间】:2019-11-09 00:45:34
【问题描述】:
我正在 xcode 中创建一个应用程序,向用户询问一系列问题并输入答案。 (别担心,我的问题与 xcode 无关)问题和答案都存储在数组中,并且我有一个 if-else 语句可以打印出问题并识别答案。我只有 5 个问题。用户提交问题 5 的答案后,应用程序崩溃并出现“线程 1:致命错误:索引超出范围”的错误消息。如何让 if-else 语句识别出数组中的问题已用完并让程序继续执行其他代码行?
我已经尝试过一系列不同类型的循环,例如 while、repeat、switch 语句和 for 循环。它们都没有 if-else 语句那么成功(这意味着它们比 if-else 更快地崩溃)。我还尝试在原始语句中创建一个 if-else。例如,我试过: 如果 (x >= 6){ 返回 } 但是,我仍然收到相同的“索引超出范围”错误。
let question = ["What is the number 1?", "What is the number 2?",
"What is the number 3?", "What is the number 4?", "What is the
number 5?"]
let answer = ["1", "2", "3", "4", "5"]
var x = 0
@IBAction func submissionButton(_ sender: Any) {
if answerBox.text! == answer[x]
{
x += 1
print("correct")
question.text = question[x]
answerBox.text = ""
}
else if (x >= 6)
{
print("done")
return
{
else
{
print("wrong")
answerBox.text = ""
}
}
每当我运行程序并输入问题时,应用程序都会在我回答“问题 5 是什么?”后崩溃。我收到错误“线程 1:致命错误:索引超出范围”。但是,我希望终端打印“完成”。
【问题讨论】:
-
您正在访问数组中不存在的索引。
-
在尝试使用之前检查
x的值。并且不要对数字 6 进行硬编码。与数组计数进行比较。 -
如果 x >= answer.length 或 x >= question.length,则无法继续执行方法。
标签: ios swift if-statement