Lou Franco
Posted on January 12, 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 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
itemDict
so that it has all of the elements.Use a
for in
loop to print out the values in thetodo
arrayUse a
for in
loop with a(key, value)
to iterate over theitemDict
and count the number of items that are done.Use a
while
loop to print two items from thetodo
array.
Hint: start with:
var itemsToPrint = 2
var i = 0
and usei
as an index into thetodo
array. You will use bothitemsToPrint
andi
in thewhile
conditional.Write that same loop using
repeat-while
.Change
itemsToPrint
to3
and note what happens to each loop. Now change it to0
and note what happens.Write the same loop using
for in
ontodo
andbreak
when you have printed enough items.Write the same loop using
for in
onitemDict
andbreak
when you have printed enough items. Remember, we just want thetodo
items (the keys with their associated value set to false)Write the same loop as above, but use
continue
when you encounter adone
item (check for that first).
Next:
The next article will provide exercises for the Functions chapter.
Posted on January 12, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.