I use if...else with a @State property to switch between the settings view and the game view. The settings view is the default view when the App launches, so whenever the game view loads, the data needed are already generated.
It works great.
Now I want to simplify the interaction so the user doesn't have to switch between two views. They can do settings and generate a new game, then start playing all on the same page.
The problem is I cannot find a way to generate initial questions when the app first launches(when the game generation function is never called yet)
This is my Question struct:
struct Question: Hashable {
let a: Int
let b: Int
var correctAnswer: Int {
a * b
}
var userAnswerSubmit: Int?
var isCorrect: Bool {
userAnswerSubmit == correctAnswer
}
}
and here's my initialization:
init() {
levelPicker = 0
numberOfQuestionsPicker = 0
questionAt = 0
userAnswer = ""
questions = {
var tempQuestions: [Question] = []
for _ in ( 0 ..< numberOfQuestions ) {
let newQuestion = Question(a: Int.random(in: 1...levelSelected), b: Int.random(in: 1...levelSelected))
tempQuestions.append(newQuestion)
}
return tempQuestions
}()
}
After this, I can correctly get the length of the questions
array by questions.count
. However, when I try to get the properties of a Question instance, say, questions[0].a
, I always get fatal error of "Index out of range".
Can someone please help me understand what's going on and how to solve this?