Skip to content

Exercises 6 ​

These exercises use the following type alias and array:

swift
typealias Person = (name: String, age: Int, favoriteFood: String?)

var people: [Person] = [
  (name: "Alice", age: 19, favoriteFood: "Chocolate"),
  (name: "Bob", age: 32, favoriteFood: "Pizza"),
  (name: "Charlie", age: 16, favoriteFood: nil),
  (name: "David", age: 24, favoriteFood: "Pasta"),
  (name: "Elise", age: 17, favoriteFood: "Pizza")
]

The goal of these exercises is to practice using the higher-order methods introduced in the previous chapter. To that end, avoid using loop statements and rely only on methods to solve the exercises.

You should also browse the Standard Library documentation for types Array and String. You’ll need some of their methods to solve the exercises.

Exercise 6.1 ​

Find the people whose name ends in "e".

Exercise 6.2 ​

Find the people whose name starts and ends with the same letter.

Keep in mind that a person’s name starts with an uppercase letter.

Exercise 6.3 ​

Find the names of the people that are less than 18 years old.

Exercise 6.4 ​

Find the age of the oldest person.

Try to find a solution that uses map and one that uses reduce.

Exercise 6.5 ​

Find the average age of everyone in the array.

Exercise 6.6 ​

Sort the array by age, ascending. Sort the original array; don’t create a new one.

Exercise 6.7 ​

Now that the people are sorted by age, find and print the index of "Charlie" in the array.

Exercise 6.8 ​

Find the youngest person who has pizza as a favorite food.

Try to find a solution that uses filter and one that doesn’t. Which do you think performs best?

Exercise 6.9 ​

First, find the names of the people who have pizza as a favorite food. Then, use reduce to build a nicely formatted string with these names. Finally, print this string.

For example:

  • If only Alice loves pizza, print "Alice loves pizza.".
  • If Alice and Bob love pizza, print "Alice and Bob love pizza.".
  • If Alice, Bob, and Charlie love pizza, print "Alice, Bob, and Charlie love pizza.".

If no one has pizza as a favorite food, print "No one loves pizza.".

Exercise 6.10 ​

The compactMap method is similar to map but removes transformed values that are nil. Use this method to get a list of all the favorite foods. This list may contain duplicates.

Exercise 6.11 ​

Declare and fill a dictionary favoriteFoods. This dictionary should record the favorite foods and how many people favor each food.