Leave a rating/review
We can now display and dismiss our leaderboard, but currently the leaderboard doesn’t show any real data.
What we want to do is to create a list of leaderboard entries, that is sorted by top score. But we haven’t yet talked about how to work with lists of data in Swift.
To create a list of data in Swift, you use a data type called array. An array is basically a data type that can store an ordered list of any other data type.
Here is an example of creating an array that starts out with three integers: 1, 2, and 3. You can visualize the array as 3 boxes that contain integers, standing in line.
After you create an array, you can modify the array by calling various methods on the array.
Here’s an example of calling the append method, to add 99 to the end of the array.
There’s a lot more you can do with ararys, but the easiest way to understand arrays in Swift is to try them out for yourself. And when you’re playing around with new concepts in Swift, one of the best ways to do this is with something called a Swift Playground.
A Swift playground is a special type of file you can use to run some Swift code immediately and see the result. Let’s try one out so you can see what I mean.
In Xcode, go to File\New\Playground. Select Blank, and click Next. Name it Arrays.playground.
Click the play button, and show how you can see the results in the gutter.
Show how you cna use the dropdown to move from manually run to automatically run.
Add this and show it in the console:
print("Hello!")
Delete all except the import UIKit. Type in this order:
var myInts: [Int] = [1, 2, 3]
for int in myInts {
print(int)
}
Add this:
myInts.append(99)
myInts.append(42)
myInts.sort()
And later:
myInts.isEmpty
myInts.count
myInts[2]
Show changing 2 to 99 and explain you need to be careful not to try to access an index that doesn’t exist.
Add this next:
struct LeaderboardEntry {
let points: Int
let date: Date
}
var leaderboardEntries: [LeaderboardEntry] = []
leaderboardEntries.append(LeaderboardEntry(points: 99, date: Date()))
leaderboardEntries.append(LeaderboardEntry(points: 42, date: Date()))
leaderboardEntries.sort { $0.points < $1.points }
print(leaderboardEntries)
Explain there’s a lot more you can do with arrays, that you’ll learn about in Programming with Swift: Fundamentals, but this should be the bare minimum you need to know to implement the leaderboards.