This article is part of a series on learning Swift by writing code to The Swift Programming Language book from Apple.
Read each article after you have read the corresponding chapter in the book. This article is a companion to Collection Types.
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 "04-Collection Types"
- Mine looks like this now:
Exercises for Collection Types
At this point, you should have read Collection Types 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.
After reading these next three chapters (Collection Types, Control Flow, and Functions) you'll be able to write a lot of interesting programs.
Sections
The chapter covers three collection types that are built in to Swift: Arrays, Sets, and Dictionaries.
For these exercises, we are going to imagine a simple to-do app, like Reminders.
In your Playground write code to do the following:
Arrays
Declare an array of strings named
todo(as avar) with three strings that are items to be done (e.g. "Buy milk")Add an item to the
todoarray.Declare a
varnameddoneinitialized to an empty String array.Remove the first item from the
todoarray and put it in thedonearray.Make an array called
allItemsthat is thetodoarray anddonearray appended to each other.Print all of the items in the
allItemsarray.
Sets
Declare a
varcalledtodoSetthat has the items from thetodoarrayAppend the first item of the
todoarray totodoSetPrint out the set (note that the items may be in a different order than the array and that each item is only there once)
Make a
doneSetfrom thedonearrayFind the intersection of the
todoSetanddoneSet.Find the union of the
todoSetanddoneSet.Compare the union to a set made from the
allItemsarray.
Dictionaries
Declare a mutable dictionary of Strings mapped to Bool named
itemDictAdd all of the items from the
todoarray with the associated bool set tofalseAdd all of the items from the
donearray with the associated bool set totrueRemove an item from the dictionary.
Update the bool associated with one of the items using
toggle()on the bool.Print out all of the strings and bools of the dictionary. Make sure you see one less item (removed in step 4) and that one of the items has their bool flipped (from step 5).
Next:
The next article will provide exercises for the Control Flow chapter.

Top comments (0)