If we want to check whether or not an element exists within a set, we can use the .contains() method.

We can use the following syntax to check for an element inside of a set:

  • If the item exists within the set, the expression returns true.
  • If the item does not appear in the set, the expression returns false.

Imagine we are hosting a party. Let’s create a set for all the food we currently have in the house:

var foodAtHome: Set = ["Chips", "Guacamole", "Cookies", "Pizza Bagels"]

We are about to head to the store and want to check if we already have "Salsa" at home or if we need to buy more.

We can use the following if/else statement with foodAtHome.contains("Salsa") as our conditional:

if foodAtHome.contains("Salsa") { print("We don't need any more salsa.") } else { print("Let's buy more salsa.") } // Prints: Let's buy more salsa.



Imagine owning a small coffee shop. A customer comes in asking for a "Blueberry" flavored coffee.

Create an if/else statement that checks if "Blueberry" exists within the set coffeeFlavors using .contains():

  • In the if, print "One blueberry coffee coming right up."
  • In the else, print "We do not serve that coffee flavor here."

Take this course for free

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

Or sign up using:

Already have an account?