Lou Franco
Posted on January 18, 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 Functions.
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.
Exercises for Functions
At this point, you should have read Functions 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.
For this chapter, we're going to write functions inspired by the Reminders app.
In your Playground write code to do the following
-
Copy the
todo
,done
, anditemDict
variables from the previous chapter's playground. Or use this:var todo = [ "Wash car", "Water plants", "Clean garage", "Plan dish for potluck", ] var done = [ "Grocery shopping", "Call mom", "Do laundry", "Mow lawn", ] // var itemDict: [String: Bool] = .... // Make this yourself based on the Collection Types chapter playground. // It should have the items from `todo` with the associated `Bool`
Make a new function called that takes two arrays of strings (
todo
anddone
) and returns a dictionary[String: Bool]
that makes theitemDict
. For this, you should already have the body of the function–you just need to declare the function and move the body in. Call this functionmakeItemDict
. If you are having any problems at this point, you may need to re-read the Collection Types chapter. Message me if you need help.-
You should be able to create
itemDict
like this now:var itemDict = makeItemDict(todo: todo, done: done)
-
Make a function that takes
itemDict: [String: Bool]
and returns the items that are done. Call itdoneItems
. After you do that, you can writevar done2 = doneItems(itemDict: itemDict)
Print out
done
anddone2
and note that they have the same items (they may be in a different order)Make a function that takes
itemDict: [String: Bool]
and returns the number of done items. Call itnumDone
. This should calldoneItems
to do part of the work.
We'll do more with functions in the next article.
Next:
The next article will provide more exercises for functions. This is a big topic.
Posted on January 18, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.