DEV Community

Lou Franco
Lou Franco

Posted on • Updated on • Originally published at app-o-mat.com

The Swift Programming Language Companion: Control Flow

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.

  1. Add more elements to both arrays and then recreate the itemDict so that it has all of the elements.

  2. Use a for in loop to print out the values in the todo array

  3. Use a for in loop with a (key, value) to iterate over the itemDict and count the number of items that are done.

  4. Use a while loop to print two items from the todo array.
    Hint: start with:
    var itemsToPrint = 2
    var i = 0
    and use i as an index into the todo array. You will use both itemsToPrint and i in the while conditional.

  5. Write that same loop using repeat-while.

  6. Change itemsToPrint to 3 and note what happens to each loop. Now change it to 0 and note what happens.

  7. Write the same loop using for in on todo and break when you have printed enough items.

  8. Write the same loop using for in on itemDict and break when you have printed enough items. Remember, we just want the todo items (the keys with their associated value set to false)

  9. Write the same loop as above, but use continue when you encounter a done item (check for that first).

Next:

The next article will provide exercises for the Functions chapter.

Top comments (0)