BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

Showing the player’s score with an alert

Paul Hudson    @twostraws   

In order for this game to be fun, we need to randomize the order in which flags are shown, trigger an alert telling them whether they were right or wrong whenever they tap a flag, then reshuffle the flags.

We already set correctAnswer to a random integer, but the flags always start in the same order. To fix that we need to shuffle the countries array when the game starts, so modify the property to this:

var countries = ["Estonia", "France", "Germany", "Ireland", "Italy", "Nigeria", "Poland", "Spain", "UK", "Ukraine", "US"].shuffled()

As you can see, the shuffled() method automatically takes care of randomizing the array order for us.

Now for the more interesting part: when a flag has been tapped, what should we do? We need to replace the // flag was tapped comment with some code that determines whether they tapped the correct flag or not, and the best way of doing that is with a new method that accepts the integer of the button and checks whether that matches our correctAnswer property.

Regardless of whether they were correct, we want to show the user an alert saying what happened so they can track their progress. So, add this property to store whether the alert is showing or not:

@State private var showingScore = false

And add this property to store the title that will be shown inside the alert:

@State private var scoreTitle = ""

So, whatever method we write will accept the number of the button that was tapped, compare that against the correct answer, then set those two new properties so we can show a meaningful alert.

Add this directly after the body property:

func flagTapped(_ number: Int) {
    if number == correctAnswer {
        scoreTitle = "Correct"
    } else {
        scoreTitle = "Wrong"
    }

    showingScore = true
}

We can now call that by replacing the // flag was tapped comment with this:

flagTapped(number)

We already have number because it’s given to us by ForEach, so it’s just a matter of passing that on to flagTapped().

Before we show the alert, we need to think about what happens when the alert is dismissed. Obviously the game shouldn’t be over, otherwise the whole thing would be over immediately.

Instead we’re going to write an askQuestion() method that resets the game by shuffling up the countries and picking a new correct answer:

func askQuestion() {
    countries.shuffle()
    correctAnswer = Int.random(in: 0...2)
}

That code won’t compile, and hopefully you’ll see why pretty quickly: we’re trying to change properties of our view that haven’t been marked with @State, which isn’t allowed. So, go to where countries and correctAnswer are declared, and put @State private before them, like this:

@State private var countries = ["Estonia", "France", "Germany", "Ireland", "Italy", "Nigeria", "Poland", "Spain", "UK", "Ukraine", "US"].shuffled()
@State private var correctAnswer = Int.random(in: 0...2)

And now we’re ready to show the alert. This needs to:

  1. Use the alert() modifier so the alert gets presented when showingScore is true.
  2. Show the title we set in scoreTitle.
  3. Have a dismiss button that calls askQuestion() when tapped.

So, put this at the end of the ZStack in the body property:

.alert(scoreTitle, isPresented: $showingScore) {
    Button("Continue", action: askQuestion)
} message: {
    Text("Your score is ???")
}

Yes, there are three question marks that should hold a score value – you’ll be completing that part soon!

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.8/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.