This article is part of a series on learning Swift by writing code to The Swift Programming Language book from Apple. This is the second 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 Enumerations.
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 "08-Enumerations"
Exercises for Enumerations
At this point, you should have read Enumerations 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 Enumeration types and use Associated Values.
For these exercises, we are going to imagine a simple media playing app.
In your Playground write code to do the following:
- Declare an enumeration called
Genreand add cases forjazz,rock,rap,country, andfolk. - Write a function called
genreNamethat takes aGenrevalue and uses aswitchto return a string with the name of the genre. So, "Jazz" for.jazzand "Rap" for.rap. - Call
genreNamewith someGenrevalues. - Extend
Genreto implementCaseIterableand write afor inloop to print out all of the genres usingGenre.allCases - Change
Genreto extendStringand changegenreNameto usegenre.rawValueinstead of aswitch - Make another enumeration called
MediaTypeand add cases formusic,podcast,audioBook - Add an associated value for
musicof typeGenre - Write a function called
mediaTitlethat takes aMediaTypevalue and uses aswitchto return a string with the name of the name of the media type. If it'smusic, make sure to use the associatedgenre. - Call
mediaTitlewith someMediaTypevalues.
Next
The next article will provide exercises for the Structures and Classes chapter.
Top comments (0)