Your First iOS & SwiftUI App: Polishing the App

Mar 1 2022 · Swift 5.5, iOS 15, Xcode 13

Part 4: A Second Screen

37. Intro to Swift Arrays

Episode complete

Play next episode

About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 36. Display a Second Screen Next episode: 38. Challenge: Leaderboard Data Model
Transcript: 37. Intro to Swift Arrays

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:


Delete all except the import UIKit. Type in this order:

var myInts: [Int] = [1, 2, 3]
for int in myInts {

Add this:


And later:


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 }

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.