TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Day 35: How do I generate data when initializing a view?

Forums > 100 Days of SwiftUI

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?

1      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.