The Swift Programming Language Companion: Collection Types

by Lou Franco

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:

  1. Choose File > New > Playground Page
  2. Rename the page to "04-Collection Types"
  3. Mine looks like this now:

Xcode Playground folder structure

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.


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:

  1. Declare an array of strings named todo (as a var) with three strings that are items to be done (e.g. "Buy milk")

  2. Add an item to the todo array.

  3. Declare a var named done initialized to an empty String array.

  4. Remove the first item from the todo array and put it in the done array.

  5. Make an array called allItems that is the todo array and done array appended to each other.

  6. Print all of the items in the allItems array.

  1. Declare a var called todoSet that has the items from the todo array

  2. Append the first item of the todo array to todoSet

  3. 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)

  4. Make a doneSet from the done array

  5. Find the intersection of the todoSet and doneSet.

  6. Find the union of the todoSet and doneSet.

  7. Compare the union to a set made from the allItems array.

  1. Declare a mutable dictionary of Strings mapped to Bool named itemDict

  2. Add all of the items from the todo array with the associated bool set to false

  3. Add all of the items from the done array with the associated bool set to true

  4. Remove an item from the dictionary.

  5. Update the bool associated with one of the items using toggle() on the bool.

  6. 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).


The next article will provide exercises for the Control Flow chapter.

Next Article: The Swift Programming Language Companion: Control Flow

Never miss an article

Get more articles like this in your inbox.