我正在构建一个测验应用程序,但收到此错误:Swift/ContigouslyArrayBuffer.swift:600: 致命错误:索引超出范围。这是被标记的代码片段: choice2.setTitle(answerChoices[1], for: .normal)。在有问题的文件中,第 40 行之后代码一直崩溃。
这是视图控制器:
// ViewController.swift
// Quizzler-iOS13
// Created by 3N0Z on 22/09/2023.
import AVFoundation
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var finishedQuiz: UIButton!
@IBOutlet weak var scoreLalbel: UILabel!
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var progressBar: UIProgressView!
@IBOutlet weak var choice1: UIButton!
@IBOutlet weak var choice2: UIButton!
@IBOutlet weak var choice3: UIButton!
var quizBrain = QuizBrain()
override func viewDidLoad() {
super.viewDidLoad()
updateUI()
}
func endQuiz () {
if quizBrain.questionNumber == 10 {
finishedQuiz.alpha = 1
choice1.alpha = 0
choice2.alpha = 0
choice3.alpha = 0
}
}
@IBAction func answerButtonPressed(_ sender: UIButton) {
let userAnswer = sender.currentTitle!
let userGotItRight = quizBrain.checkAnswer(userAnswer: userAnswer)
if userGotItRight {
sender.backgroundColor = UIColor.green
} else {
sender.backgroundColor = UIColor.red
}
quizBrain.nextQuestion()
Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(updateUI), userInfo: nil, repeats: false)
}
func start(){
finishedQuiz.alpha = 0
}
@objc func updateUI() {
questionLabel.text = quizBrain.getQuestionText()
//Need to fetch the answers and update the button titles using the setTitle method.
let answerChoices = quizBrain.getAnswers()
choice1.setTitle(answerChoices[0], for: .normal)
choice2.setTitle(answerChoices[1], for: .normal)
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())"
}
}
这是问题结构:
// Question.swift
// Quizzler-iOS13
//
// Created by 3N0Z on 2023-09-12.
import Foundation
struct Question {
let text: String
//Multiple choice questions have multiple answers, an Array of Strings would work for our quiz data.
let answers : [String] // <- Here
//Look at the data in the quiz array, there is a seperate string that is the correctAnswer.
let correctAnswer: String
//The initialiser needs to be updated to match the new multiple choice quiz data.
init(q: String, a: [String], rightAnswer: String) { // <- Here
text = q
answers = a
correctAnswer = rightAnswer
}
}
这些是文件名为 QuizBrain 的问题:
// QuizBrain.swift
// Quizzler-iOS13
//
// Created by 3N0Z on 2023-09-29.
import Foundation
struct QuizBrain {
public var questionNumber = 0
var score = 0
let quiz = [
Question(q: "Which is the largest organ in the human body?", a: ["Heart", "Skin", "Large Intestine"], rightAnswer: "Skin"),
Question(q: "Five dollars is worth how many nickels?", a: ["25", "50", "100"], rightAnswer: "100"),
Question(q: "What do the letters in the GMT time zone stand for?", a: ["Global Meridian Time", "Greenwich Mean Time", "General Median Time"], rightAnswer: "Greenwich Mean Time"),
Question(q: "What is the French word for 'hat'?", a: ["Chapeau", "Écharpe", "Bonnet"], rightAnswer: "Chapeau"),
Question(q: "In past times, what would a gentleman keep in his fob pocket?", a: ["Notebook", "Handkerchief", "Watch"], rightAnswer: "Watch"),
Question(q: "How would one say goodbye in Spanish?", a: ["Au Revoir", "Adiós", "Salir"], rightAnswer: "Adiós"),
Question(q: "Which of these colours is NOT featured in the logo for Google?", a: ["Green", "Orange", "Blue"], rightAnswer: "Orange"),
Question(q: "What alcoholic drink is made from molasses?", a: ["Rum", "Whisky", "Gin"], rightAnswer: "Rum"),
Question(q: "What type of animal was Harambe?", a: ["Panda", "Gorilla", "Crocodile"], rightAnswer: "Gorilla"),
Question(q: "Where is Tasmania located?", a: ["Indonesia", "Australia", "Scotland"], rightAnswer: "Australia"),
Question(q: "Which city is home to the Brandenburg Gate?", a: ["Vienna", "Zurich", "Berlin"], rightAnswer:"Berlin"),
Question(q: "Where was the first example of paper money used?", a: ["China","Turkek","Greece"], rightAnswer:"China"),
Question(q: "Who is generally considered the inventor of the motor car?", a: ["Henry Ford", "Karl Benz", "Henry M. Leland"], rightAnswer:"Karl Benz"),
Question(q: "What number was the Apollo mission that successfully put a man on the moon for the first time in human history? ", a: ["Apollo 11", "Apollo 12", "Apollo 13"], rightAnswer:"Apollo 11"),
Question(q: "Which of the following languages has the longest alphabet?", a: ["Greek", "Russian", "Arabic"], rightAnswer:"Russian"),
Question(q: "Who was the lead singer of the band The Who?", a: ["Roger Daltrey", "Don Henley", "Robert Plant"], rightAnswer:"Roger Daltrey"),
Question(q: "What spirit is used in making a Tom Collins?", a: ["Vodka", "Rum", "Gin"], rightAnswer:"Gin"),
Question(q: "The fear of insects is known as what?", a: ["Entomophobia", "Arachnophobia", "Ailurophobia"], rightAnswer:"Entomophobia"),
Question(q: " What was the name of the Franco-British supersonic commercial plane that operated from 1976-2003?", a: ["Accord", "Concorde", "Mirage"], rightAnswer:"Concorde"),
Question(q: "Which horoscope sign is a fish?", a: ["Aquarius", "Cancer", "Pisces"], rightAnswer:"Pisces"),
Question(q: "What is the name for the Jewish New Year?", a: ["Hanukkah", "Rosh Hashanah", "Kwanza"], rightAnswer:"Rosh Hashanah"),
Question(q: "What is the longest word in the English language?", a: ["Antidisestablishmentarianism", "Hippopotomonstrosesquippedaliophobia", "Floccinaucinihilipilification"], rightAnswer:"Antidisestablishmentarianism"),
Question(q: "What is the name of the world’s smallest horse?", a: ["Falabella", "Shetland pony", "Miniature horse"], rightAnswer:"Miniature horse"),
Question(q: "What is Benedictine monk Dom Pierre Pérignon rumored to have created?", a: ["Tomato ketchup", "Champagne", "French fries"], rightAnswer:"Champagne"),
Question(q: "Which country drinks the most amount of coffee per person? ", a: ["Finland, Italy, Colombia "], rightAnswer:"Finland"),
Question(q: "What is the collective name for a group of unicorns?", a: ["A sparkle", "A spell", "A blessing"], rightAnswer:"A blessing"),
Question(q: "What is the most common color of toilet paper in France?", a: ["Pink", "White", "Blue"], rightAnswer:"Pink"),
Question(q: "How many years old is the world’s oldest piece of chewing gum? ", a: ["100", "2,500", "5,700"], rightAnswer:"5,700"),
Question(q: "How many times per day does the average American open their fridge?", a: ["5", "33", "22"], rightAnswer:"33"),
Question(q: "What color is an airplane’s famous black box?", a: ["Red", "Orange", "Black"], rightAnswer:"Orange"),
Question(q: "On a boat, what is the opposite of port?", a: ["Bow", "Starboard", "Deck"], rightAnswer:"Starboard"),
Question(q: "In what language is the phrase ‘Hakuna Matata’?", a: ["Dutch", "Swahili", "Yoruba"], rightAnswer:"Swahili"),
Question(q: "Did you enjoy this quiz?", a: ["Yes & continue", "No & continue", "Continue"], rightAnswer:"You will never get his one"),
]
func getQuestionText() -> String {
return quiz[questionNumber].text
}
//Need a way of fetching the answer choices.
func getAnswers() -> [String] {
return quiz[questionNumber].answers
}
func getProgress() -> Float {
return Float(questionNumber) / Float(quiz.count)
}
mutating func getScore() -> Int {
return score
}
mutating func nextQuestion() {
if questionNumber + 1 < quiz.count {
questionNumber += 1
} else {
questionNumber = 0
}
}
mutating func checkAnswer(userAnswer: String) -> Bool {
//Need to change answer to rightAnswer here.
if userAnswer == quiz[questionNumber].correctAnswer {
score += 1
return true
} else {
return false
}
}
}
我尝试检查代码是否有错误,并在 StackOverflow、Reddit 和在线上查找解决方案,但没有任何效果。发送帮助。
避免
Fatal error: Index out of range
的一个简单稳健的修复方法是在访问数组元素之前先检查索引。
在您的
QuizBrain
(和其他地方)中,我建议每当
你访问 quiz
数组,你检查
索引,例如:
if questionNumber < quiz.count { .... quiz[questionNumber] }
同样使用
answerChoices
时,先检查索引。
if 2 < answerChoices.count {
choice1.setTitle(answerChoices[0], for: .normal)
choice2.setTitle(answerChoices[1], for: .normal)
choice3.setTitle(answerChoices[2], for: .normal)
}
这样您就不会收到致命错误:索引超出范围。