The Swift Programming Language Companion: Subscripts

by Lou Franco

This article is part of a series on learning Swift by writing code to The Swift Programming Language book from Apple. This is the seventh article in Section 2 (here is Section 1)

Read each article after you have read the corresponding chapter in the book. This article is a companion to Subscripts.

Set up a reading environment

If you are jumping around these articles, make sure you read the Introduction to see my recommendation for setting up a reading environment.

To add a new page, in Xcode:

  1. Choose File > New > Playground Page
  2. Rename the page to "12-Subscripts"

Exercises for Subscripts

At this point, you should have read Subscripts in The Swift Programming Language. You should have a Playground page for this chapter with code in it that you generated while reading the book.


The chapter covers how to declare Subscripts inside of Structures and Classes

For these exercises, we are going to imagine a simple media playing app.

In your Playground write code to do the following:

  1. Declare a struct called MusicPlayer
  2. Add a private constant of type [String] called songs and initialize it with a few names of songs. For example: "Style", "Shake it Off", "Bad Blood", "Welcome to New York"
  3. Add a computed get property called count that returns the count of the songs array
  4. Add a subscript getter that takes an index and returns the corresponding song from the songs array.
  5. Write some test code that constructs a MusicPlayer and uses count and the subscript to get the names of the songs.


The next article will provide exercises for the Inheritance chapter.

Next Article: The Swift Programming Language Companion: Inheritance

Never miss an article

Get more articles like this in your inbox.