NEW: Nominations are now open for the 2019 Swift Community Awards! >>

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!

SAVE 20% ON iOS CONF SG The largest iOS conference in Southeast Asia is back in Singapore for the 5th time in January 2020, now with two days of workshops plus two days of talks on SwiftUI, Combine, GraphQL, and more! Save a massive 20% on your tickets by clicking on this link.

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift 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: 5.0/5