I’m building a vocabulary quiz app in Swift and using Airtable as my backend database. I managed to get the questions and choices displaying correctly, but I’m having trouble with answer validation.
Here’s my current code for loading quiz data:
func loadQuizData() {
let endpoint = "https://api.airtable.com/v0/appXYZ123/QuizTable?maxRecords=15&view=Main"
let token = "myToken"
let requestURL = URL(string: endpoint)!
var apiRequest = URLRequest(url: requestURL)
apiRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
URLSession.shared.dataTask(with: apiRequest) { (responseData, urlResponse, requestError) in
let jsonDecoder = JSONDecoder()
guard let responseData = responseData else { return }
do {
let quizData = try jsonDecoder.decode(QuizResponse.self, from: responseData)
DispatchQueue.main.async {
self.questionCounter.text = "Question \(self.currentQuestion+1)"
self.questionText.text = quizData.records[self.currentQuestion].fields.questionText
self.choiceOne.setTitle(quizData.records[self.currentQuestion].fields.choiceOne, for: .normal)
self.choiceTwo.setTitle(quizData.records[self.currentQuestion].fields.choiceTwo, for: .normal)
self.choiceThree.setTitle(quizData.records[self.currentQuestion].fields.choiceThree, for: .normal)
self.choiceFour.setTitle(quizData.records[self.currentQuestion].fields.choiceFour, for: .normal)
}
} catch {
print("Error: \(error)")
}
}.resume()
}
The problem happens when I try to check if the user picked the right answer. My quiz data becomes nil and crashes the app. How can I properly store and access the correct answers for comparison?