The third challenge was to make so if the user gives an incorrect flag guess, the alert message will display something like "Wrong, that's France's flage" or something like that.
I tried putting the alert modifier inside an if/else statement but I can't get it to work. I'm getting "function declares an opaque return type" and "cannot convert return expression of type 'ZStack' . . . " Any better ways? I'm new to Swift and programming in general so any help would be awesome!
Thanks!
import SwiftUI
struct ContentView: View {
@State var countries = ["Estonia", "France", "Germany", "Ireland", "Italy", "Poland", "Russia", "Spain", "UK", "US",].shuffled()
@State var correctAnswer = Int.random(in: 0...2)
@State private var showingScore = false
@State private var scoreTitle = ""
@State private var userScore = 0
var body: some View {
ZStack {
LinearGradient(gradient: Gradient(colors: [.blue, .black]), startPoint: .top, endPoint: .bottom)
.edgesIgnoringSafeArea(.all)
VStack(spacing: 30)
{
VStack {
Text("Tap the flag of ")
.foregroundColor(.white)
Text(countries[correctAnswer])
.font(.largeTitle)
.fontWeight(.black)
.foregroundColor(.white)
}
ForEach(0 ..< 3) { number in
Button(action: {
self.flagTapped(number)
}) {
Image(self.countries[number])
.renderingMode(.original)
.clipShape(Capsule())
.overlay(Capsule().stroke(Color.black, lineWidth: 1))
.shadow(color: .black, radius: 2)
}
}
VStack {
Text("Current Score: \(String(userScore))")
.foregroundColor(.white)
}
Spacer()
}
if scoreTitle == "Wrong" {
.alert(isPresented: $showingScore) {
Alert(title: Text(scoreTitle), message: Text("Wrong! That's \(countries[number])'s flag. Your score is \(String(userScore))"), dismissButton: .default(Text("Continue")) {
self.askQuestion()
})
}
} else {
.alert(isPresented: $showingScore) {
Alert(title: Text(scoreTitle), message: Text("Your score is \(String(userScore))"), dismissButton: .default(Text("Continue")) {
self.askQuestion()
})
}
}
}
}
func flagTapped(_ number: Int) {
if number == correctAnswer {
scoreTitle = "Correct"
userScore += 1
}
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()
}
}