Learn

If we want to go through every individual value contained in a set, we can use a for-in loop!

To iterate over every item of a set, we can use this syntax:

for Value in setName {
  // Body of loop
}

Imagine we are making cookies. Let’s create a set that stores the necessary ingredients for baking chocolate chip cookies:

var chocoChipCookies: Set = ["Flour", "Chocolate Chips", "Butter", "Eggs", "Sugar", "Baking Powder"]

We can use a for-in loop that will print() all the ingredients we need:

for ingredient in chocoChipCookies { print(ingredient) }

Our placeholder, ingredient, stores the value of the current iteration. When we run this code, we will receive something similar to the following output:

Flour Chocolate Chips Eggs Baking Powder Butter Sugar

Sets are unordered, so this output could look different every time we run our code.

Instructions

1.

In Vacation.swift, the set thingsToPack contains items we want to bring on a trip. The other set, suitcase, is an empty set we will populate to reflect the items we have packed.

Use a for-in loop to iterate through each element in the set thingsToPack.

Name the placeholder item.

2.

Inside the body of the loop, use .insert() to add item to the set suitcase.

Outside the loop, print() the value of suitcase.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?