【问题标题】:How to you end an if-else loop without the program crashing?如何在程序不崩溃的情况下结束 if-else 循环?
【发布时间】: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


【解决方案1】:

您检查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
}



【讨论】:

    【解决方案2】:

    当您检查 answerBox.text 时,您的错误出现在您的 submitButton 函数的第一行! == 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 = ""
        }
    }
    

    【讨论】:

    • 我完全尝试了您的代码,但在question.text = question[x] 行仍然收到错误消息和消息“线程 1:致命错误:索引超出范围”
    • if x >= question.count {。你需要>=,而不是>。真的你只需要==>= 更安全。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    相关资源
    最近更新 更多