Lou Franco
Posted on January 11, 2020
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
todo
array.Declare a
var
nameddone
initialized to an empty String array.Remove the first item from the
todo
array and put it in thedone
array.Make an array called
allItems
that is thetodo
array anddone
array appended to each other.Print all of the items in the
allItems
array.
Sets
Declare a
var
calledtodoSet
that has the items from thetodo
arrayAppend the first item of the
todo
array totodoSet
Print 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
doneSet
from thedone
arrayFind the intersection of the
todoSet
anddoneSet
.Find the union of the
todoSet
anddoneSet
.Compare the union to a set made from the
allItems
array.
Dictionaries
Declare a mutable dictionary of Strings mapped to Bool named
itemDict
Add all of the items from the
todo
array with the associated bool set tofalse
Add all of the items from the
done
array with the associated bool set totrue
Remove 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.
Posted on January 11, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.