Follow along at https://www.hackingwithswift.com/100/21.
This day covers the third and final part of Project 2: Guess the Flag
in Hacking with Swift.
I have a separate repository where I've been creating projects alongside the material in the book. And you can find Project 2 here.
However, the main focus of this day was extending the finished app according to a set of challenges. With that in mind, I copied the old finished project to this repo and got started.
Try showing the player’s score in the navigation bar, alongside the flag to guess.
Keep track of how many questions have been asked, and show one final alert controller after they have answered 10. This should show their final score
When someone chooses the wrong flag, tell them their mistake in your alert message – something like “Wrong! That’s the flag of France,” for example.
My original approach for this project was to create a dictionary of flagFilePathsAndNames
, which ended up being used somewhat awkwardly — storing things like a correctFlagKey
key and flagChoiceKeys
.
Having since learned a lot more about modeling data in Swift, I took a stab at modeling a Flag
struct that stored an assetName
and displayName
for the flag. This made it possible to keep the following three items in ViewController
:
var flags: [Flag] = []
var flagChoices: [Flag] = []
var correctFlag: Flag!
These items, then, provided clear and definitive access for the properties of each flag:
func askQuestion() {
flagChoices = Array(flags.shuffled()[..<3])
correctFlagTag = Int.random(in: 0..<3)
correctFlag = flagChoices[correctFlagTag]
title = "Which flag belongs to \(correctFlag.displayName)?"
for (index, button) in [button1, button2, button3].enumerated() {
button?.setImage(UIImage(named: flagChoices[index].assetName), for: .normal)
}
}