Swift Quiz应用触发Index out of range错误,请求技术支持
解决Quiz应用的数组越界崩溃问题
错误详情
运行时触发致命错误:Swift/ContiguousArrayBuffer.swift:600: Fatal error: Index out of range,触发代码为choice2.setTitle(answerChoices[1], for: .normal),在QuizBrain文件第40行后程序持续崩溃。
问题根源
检查QuizBrain.swift中的quiz数组,发现其中一个Question实例的answers参数错误地将三个选项合并成了单个字符串,导致该问题的选项数组长度仅为1:
// 错误写法:answers数组只有1个元素 Question(q: "Which country drinks the most amount of coffee per person? ", a: ["Finland, Italy, Colombia "], rightAnswer:"Finland"),
而updateUI方法中直接通过索引0、1、2访问选项数组,当程序运行到这个问题时,数组长度不足,直接触发越界崩溃。
修复方案
1. 修正错误的Question实例
将该问题的answers拆分为三个独立的字符串元素:
// 正确写法:拆分三个独立选项 Question(q: "Which country drinks the most amount of coffee per person? ", a: ["Finland", "Italy", "Colombia"], rightAnswer:"Finland"),
2. 添加防御性代码(可选)
为避免后续因类似数据错误再次崩溃,在updateUI中增加数组长度判断,再设置按钮标题:
@objc func updateUI() { questionLabel.text = quizBrain.getQuestionText() let answerChoices = quizBrain.getAnswers() // 先清空按钮标题,避免残留旧内容 choice1.setTitle(nil, for: .normal) choice2.setTitle(nil, for: .normal) choice3.setTitle(nil, for: .normal) // 根据实际选项数量设置对应按钮 if answerChoices.count > 0 { choice1.setTitle(answerChoices[0], for: .normal) } if answerChoices.count > 1 { choice2.setTitle(answerChoices[1], for: .normal) } if answerChoices.count > 2 { choice3.setTitle(answerChoices[2], for: .normal) } choice1.backgroundColor = UIColor.clear choice2.backgroundColor = UIColor.clear choice3.backgroundColor = UIColor.clear progressBar.progress = quizBrain.getProgress() scoreLalbel.text = "Score: \(quizBrain.getScore())" }
3. 优化endQuiz逻辑(可选)
当前endQuiz仅判断questionNumber ==10就结束,但quiz数组包含更多问题,建议改为判断是否到达最后一题:
func endQuiz () { if quizBrain.questionNumber == quizBrain.quiz.count - 1 { finishedQuiz.alpha = 1 choice1.alpha = 0 choice2.alpha = 0 choice3.alpha = 0 } }
并在updateUI方法末尾调用endQuiz(),确保到达最后一题时正确显示结束按钮。
内容的提问来源于stack exchange,提问作者Shivashannt Dineshkumar
相关产品推荐
相关产品推荐

