NEW: Get your ticket to Hacking with Swift Live 2020! >>

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", "Russia", "Spain", "UK", "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:

self.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", "Russia", "Spain", "UK", "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(isPresented: $showingScore) {
    Alert(title: Text(scoreTitle), message: Text("Your score is ???"), dismissButton: .default(Text("Continue")) {
        self.askQuestion()
    })
}

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

SPONSORED Why the top iOS apps rely on Instabug for crash reporting. Crash reporting + Bug reporting + Customizable in-app surveys all in one SDK. Know which line of code caused the crash along with network logs, repro steps, and the session profiler to identify and resolve severe crashes quickly. See more detailed features comparison and try Instabug for free here.

Support my work on Patreon

BUY OUR BOOKS
Buy Pro Swift 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 (Vapor Edition) 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 Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.8/5