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:
- Choose File > New > Playground Page
- 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.
Exercises
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:
- Add a method to
Player
calledisPlaying
that returns aBool
. It should be true ifcurrentSong
is not nil. - Add a method to
Player
calledplay
that takes asong
parameter. It should setcurrentSong
. The parameter should not be optional.
Harder challenge:
- Add methods
pause
andresume
(taking no parameters and returningVoid
). To do this, you might need more properties. Make sureisPlaying
andcurrentSong
behave reasonably.
Next
The next article will provide exercises for the Subscripts chapter.
Top comments (0)