如何在不导致程序崩溃的情况下结束if-else循环?

时间:2019-11-08 00:09:25

标签: ios swift if-statement

我正在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:致命错误:索引超出范围”。但是,我希望终端打印“完成”。

2 个答案:

答案 0 :(得分:0)

您检查if (x >= 6)来查看您是否已完成,因此,当x = 5时,您还不完整。但是,数组包含五项,但是由于数组的索引为0,因此只有索引0到4的条目。因此,在if answerBox.text! == answer[x]中,您将得到索引超出范围的错误,因为答案[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
}



答案 1 :(得分:0)

当您检查answerBox.text时,您的错误发生在submittingButton函数的第一行! == answer [x],当x已经增加到6时。(此外,如下面的rmaddy所述,当x == 5时,必须为x> = question.count才能捕获它。 试试这个...

@IBAction func submissionButton(_ sender: Any) {
    if x >= question.count {
        print("done")
        return
    }
    if answerBox.text! == answer[x] {
        x += 1
        print("correct")
        question.text = question[x]
        answerBox.text = ""
    } else {
        print("wrong")
        answerBox.text = ""
    }
}
相关问题