This article is part of a series on learning Swift by writing code to The Swift Programming Language book from Apple. This is the first 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 Closures.
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 "07-Closures"
Exercises for Closures
At this point, you should have read Closures 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 create and call closures and the concept of capturing.
For these exercises, we are going to imagine a simple media playing app.
In your Playground write code to do the following:
- Declare a Boolean variable called
isPlaying
and set it tofalse
. - Declare a constant called
play
that is a closure type that takes no arguments and returnsVoid
. Initialize it with a closure that prints the word "Play" and setsisPlaying
totrue
when called. - Call
play
. PrintisPlaying
(it should be true) - Make a constant called
stop
which is likeplay
but prints "Stop" and setsisPlaying
tofalse
- Call
stop
and printisPlaying
- Under
isPlaying
, Declare an optionalString
variable calledcurrentSong
- Add a
String
argument to play calledsong
and setcurrentSong
to it inside the closure. - Update your call to play pass a
song
argument - Print
currentSong
after callingplay
- Declare a
playList
array ofStrings
and initialize it with 5 songs. - Sort the list by the length of the song name
Next
The next article will provide exercises for the Enumerations chapter.
Top comments (0)