I am completing a swift challenge and below is the program so far. No doubt it is full of problems but I am slowly working them out. It is a maths game that presents the user with a random multiplication question. They insert their answer and it is either right or wrong. The thing that has me stumped at the moment is using the users input. I have a textfield with a $answer to accept their answer. I also have a func called checkAnswer but am not sure how to pass in the textfield value for answer. Can anyone assist please??
import SwiftUI
struct Test1: View {
@State private var numberOfGames = 5
@State private var gameNumber = 0
@State private var showingGameOver = false
@State private var firstChoice: [Int] = [0, 1, 2, 3]
@State private var secondChoice: [Int] = [0, 1, 2, 3]
@State private var score = 0
@State private var answer = 0
@State private var correctAnswer = 0
var body: some View {
NavigationView {
VStack {
Form {
Section("Choose 5, 10, or 15 games") {
Stepper("\(numberOfGames) Games", value: $numberOfGames, in: 5...15, step: 5)
}
Button {
createGame()
} label: {
Text("New Game")
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(20)
Text("This is game \(gameNumber) of \(numberOfGames) games.")
Section {
HStack {
Text("\(firstChoice[0]) x \(secondChoice[0]) = ")
TextField("Enter your answer here", value: $answer)
// TextField("Enter your answer here", value: $answer, onCommit: {
// checkAnswer
}
}
}
}
.alert("The game is over.", isPresented: $showingGameOver) {
Button("Game over.", action: Reset)
}
}.navigationTitle("Maths Quiz")
}
func checkAnswer() {
correctAnswer = firstChoice[0] * secondChoice[0]
if correctAnswer == answer {
}
}
func createGame() {
var firstList = [Int]()
var secondList = [Int]()
for _ in 0...12 {
firstList.append(Int.random(in: 0...12))
}
for _ in 0...12 {
secondList.append(Int.random(in: 0...12))
}
firstChoice = firstList.shuffled()
secondChoice = secondList.shuffled()
gameNumber += 1
if gameNumber == numberOfGames {
showingGameOver = true
}
}
func Reset() {
score = 0
gameNumber = 1
}
}
struct Test1_Previews: PreviewProvider {
static var previews: some View {
Test1()
}
}