This article is part of a series on learning Swift by writing code to The Swift Programming Language book from Apple. This is the fourth 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 Properties.
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 "10-Properties"
Exercises for Properties
At this point, you should have read Properties 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 Properties inside of Structures and Classes. For Part 1, we're going to stick to the more common parts, stored properties, computed properties, and Type properties.
For these exercises, we are going to imagine a simple media playing app.
In your Playground write code to do the following:
- (from enumerations): Declare an enumeration called
Genre
and add cases forjazz
,rock
,rap
,country
, andfolk
. - Declare an
Artist
struct with stored propertiesname
andbirthDate
- Declare a
Song
struct with stored propertiestitle
,artist
, andgenre
- Add a computed property to
Artist
calledage
which usesbirthDate
and today’s date. - Declare a few
Artist
andSong
instances - Make a class called
Library
and add a Type property calledsongs
that is an array ofSong
structs. Initialize it with a few values.
Hints
To find today’s date: let today = Date()
To find the number of seconds between two dates:
let seconds = today.timeIntervalSince(birthDate)
Next
The next article will look at the more advanced usage of properties.
Top comments (0)