Good day all!
I am receiving the follwoing error when running the guess the flag app. If I comment out the Text(countries[correctAnswer]), the issue goes away.
Xcode: 13.1
iOS 15 Builder
import SwiftUI
@main Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ff7b1375ff8)
struct GuessTheFlagApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
Code in project:
//
// ContentView.swift
// GuessTheFlag
//
// Created by Eric Forbes on 11/29/21.
//
import SwiftUI
struct ContentView: View {
@State private var showingScore = false
@State private var scoreTitle = ""
@State private var countries = ["Estonia", "France", "Germany", "Ireland", "Italy", "Nigeria", "Poland", "Russia", "Spain", "UK", "US"].shuffled()
@State private var correctAnswer = Int.random(in: 0...2)
var body: some View {
ZStack {
Color.blue
// LinearGradient.init(colors: [.blue, .white], startPoint: .topLeading, endPoint: .bottomTrailing)
.ignoresSafeArea()
VStack(spacing: 30) {
VStack {
Text("Tap the flag of")
.foregroundColor(.white)
Text(countries[correctAnswer])
foregroundColor(.white)
}
ForEach(0..<3) { number in
Button {
flagTapped(number)
} label: {
Image(countries[number])
.renderingMode(.original)
}
}
}
}
.alert(scoreTitle, isPresented: $showingScore) {
Button("Continue", action: askQuestion)
} message: {
Text("Your score is ???")
}
}
func flagTapped(_ number: Int) {
if number == correctAnswer {
scoreTitle = "Correct"
} else {
scoreTitle = "Wrong"
}
showingScore = true
}
func askQuestion() {
countries.shuffle()
correctAnswer = Int.random(in: 0...2)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct ContentView_Previews_Dark: PreviewProvider {
static var previews: some View {
ContentView().preferredColorScheme(.dark)
}
}