The Swift Programming Language Companion: Functions

loufranco

Lou Franco

Posted on January 18, 2020

The Swift Programming Language Companion: Functions

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

  1. Copy the todo, done, and itemDict 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`
    
  2. Make a new function called that takes two arrays of strings (todo and done) and returns a dictionary [String: Bool] that makes the itemDict. 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 function makeItemDict. 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.

  3. You should be able to create itemDict like this now:

    var itemDict = makeItemDict(todo: todo, done: done)
    
  4. Make a function that takes itemDict: [String: Bool] and returns the items that are done. Call it doneItems. After you do that, you can write

    var done2 = doneItems(itemDict: itemDict)
    
  5. Print out done and done2 and note that they have the same items (they may be in a different order)

  6. Make a function that takes itemDict: [String: Bool] and returns the number of done items. Call it numDone. This should call doneItems 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.

💖 💪 🙅 🚩
loufranco
Lou Franco

Posted on January 18, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related