Hi all,
I am trying to build an struct that would contain the database of answers as well as of the questions to the multiplication table challenge. I did the following inside of a playground and it works perfectly fine (or at least the way I intend it to:
import Cocoa
struct Question {
var questions = [String]()
var answers = [Int]()
var questionsDatabase = [Array<String>]()
var answersDatabase = [Array<Int>]()
mutating func generateDatabase() {
for i in 0...12 {
for j in 0...i {
questions.append("\(i) * \(j)")
answers.append(i*j)
}
questionsDatabase.insert(questions, at: i)
answersDatabase.insert(answers, at: i)
questions.removeAll()
answers.removeAll()
}
}
}
var ourTable = Question()
ourTable.generateDatabase()
print(ourTable.questionsDatabase[3]) // shows ["3 * 0", "3 * 1", "3 * 2", "3 * 3"]
print(ourTable.questionsDatabase[3][3]) // shows 3 * 3
However, if I try to get it to work inside my main project, it always crashes with a fatal error and I can see that questions, answers, questionsDatabase, answersDatabase all have 0 values - and I cannot for the life of me tell why... :(
import SwiftUI
struct MultiplicationTable {
var questions = [String]()
var answers = [Int]()
var questionsDatabase = [Array<String>]()
var answersDatabase = [Array<Int>]()
mutating func generateDatabase() {
for i in 0...12 {
for j in 0...i {
questions.append("\(i) * \(j)")
answers.append(i*j)
}
questionsDatabase.insert(questions, at: i)
answersDatabase.insert(answers, at: i)
questions.removeAll()
answers.removeAll()
}
}
}
struct ContentView: View {
@State private var ourTable = MultiplicationTable()
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text(ourTable.questionsDatabase[3][3])
}
.onAppear {
ourTable.generateDatabase()
}
.padding()
}
}
#Preview {
ContentView()
}
Any pointers would be highly appreciated! Thank you a ton in advance!