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 Control Flow.
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 Control Flow
At this point, you should have read Control Flow 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.
Sections
The chapter covers loops and conditional statements.
For these exercises, we are going to continue using the Reminders app as inspiration for examples. We already saw for loops for many of those examples—now we'll take them further.
In your Playground write code to do the following:
Copy the todo and done arrays that you made in the previous chapter.
Add more elements to both arrays and then recreate the
itemDictso that it has all of the elements.Use a
for inloop to print out the values in thetodoarrayUse a
for inloop with a(key, value)to iterate over theitemDictand count the number of items that are done.Use a
whileloop to print two items from thetodoarray.
Hint: start with:
var itemsToPrint = 2
var i = 0
and useias an index into thetodoarray. You will use bothitemsToPrintandiin thewhileconditional.Write that same loop using
repeat-while.Change
itemsToPrintto3and note what happens to each loop. Now change it to0and note what happens.Write the same loop using
for inontodoandbreakwhen you have printed enough items.Write the same loop using
for inonitemDictandbreakwhen you have printed enough items. Remember, we just want thetodoitems (the keys with their associated value set to false)Write the same loop as above, but use
continuewhen you encounter adoneitem (check for that first).
Next:
The next article will provide exercises for the Functions chapter.
Top comments (0)