我正在 xcode 中创建一个应用程序,用户会被问到一系列问题并输入答案。 (别担心,我的问题与 xcode 无关)问题和答案都存储在数组中,我有一个 if-else 语句打印出问题并识别答案。我的数组中只有 5 个问题。一旦用户提交了问题 5 的答案,应用程序就会崩溃,并出现一条错误消息“线程 1: fatal error :索引超出范围”。如何让 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: fatal error :索引超出范围”。但是,我希望终端打印“完成”。
最佳答案
你检查if (x >= 6)
来看看你是否完成了,因此当x = 5时你还没有完成。然而,该数组包含五个项目,但因为数组是 0 索引的,所以只有索引 0 到 4 的条目。因此在 if answerBox.text! ==answer[x]
您将收到索引超出范围错误,因为answer[5] 不存在。
您需要在代码中考虑到这一点。我会首先检查是否完成,因为这意味着无论您有什么其他逻辑,您都不能使用超出范围的索引:
if x >= answers.count {
print("Done")
return
} else if answerBox.text = answers[x] {
print("Correct")
x += 1
question.text = question[x]
} else {
print("Wrong")
answerBox.text = nil
}
关于ios - 如何结束 if-else 循环而不导致程序崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58758637/