Leave a rating/review
Now that you’ve used Swift playgrounds to prototype an array of leaderboard entries, let’s integrate this into our Bullseye data model.
Just like we’ve done before, we’ll return to our old friend TDD. We’ll write a test for what we want to do together, and then it will be your job to make the test pass. Let’s get started.
Add to Game.swift:
struct LeaderboardEntry {
let score: Int
let date: Date
}
Add to Game:
var leaderboardEntries: [LeaderboardEntry] = []
Add to BullseyeTests.swift:
func testLeaderboard() {
game.startNewRound(points: 100)
XCTAssertEqual(game.leaderboardEntries.count, 1)
XCTAssertEqual(game.leaderboardEntries[0].score, 100)
game.startNewRound(points: 200)
XCTAssertEqual(game.leaderboardEntries.count, 2)
XCTAssertEqual(game.leaderboardEntries[0].score, 200)
XCTAssertEqual(game.leaderboardEntries[0].score, 100)
}
Run test, it fails.
Your challenge is to write the code so that these tests pass.
Basically, startNewRound needs to add a new entry to the leaderbordEntries array, and then sort the array. This should be very similar to what you did in the playground in the last episode.
Optionally, you may want to extract this code into a separate addToLeaderboard method, which startNewRound calls, but that is up to you.
Pause the video, and give this a shot. Good luck!
Add to Game.swift, above startNewRound:
mutating func addToLeaderboard(points: Int) {
leaderboardEntries.append(LeaderboardEntry(points: points, date: Date()))
leaderboardEntries.sort { $0.points > $1.points }
}
Add to startNewRound:
addToLeaderboard(points: points)
Show tests pass.