The Swift Programming Language Companion: Methods

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 sixth 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 Methods.

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 "11-Methods"

Exercises for Methods

At this point, you should have read Methods 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 Methods inside of Structures and Classes

For these exercises, we are going to imagine a simple media playing app. From the last two chapters, you should have something like this:

struct Song {
    let title: String

class Player {
    var currentSong: Song? {
        didSet {
            if let currentSong = currentSong {
                print("\(currentSong.title) is playing")
            } else {
                print("No song is playing")

In your Playground write code to do the following:

  1. Add a method to Player called isPlaying that returns a Bool. It should be true if currentSong is not nil.
  2. Add a method to Player called play that takes a song parameter. It should set currentSong. The parameter should not be optional.

Harder challenge:

  1. Add methods pause and resume (taking no parameters and returning Void). To do this, you might need more properties. Make sure isPlaying and currentSong behave reasonably.


The next article will provide exercises for the Subscripts chapter.

Next Article: The Swift Programming Language Companion: Subscripts

Never miss an article

Get more articles like this in your inbox.