Learn
Sets
Checking For Elements

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:

setName.contains(Value)
  • 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.

Instructions

1.

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."
Folder Icon

Take this course for free

Already have an account?