Learn
Sets
Set Operations: .subtracting()

Another set operation we can use is .subtracting(). This method creates a new set of elements by removing the overlapping data of one set from another set.

To use .subtracting() in our program, we can use this code:

var newSet = SetA.subtracting(SetB)

Any values that SetA shares with SetB will be removed and newSet will contain values found only in SetA but not in SetB.

.subtracting()

Consider the following sets: animals and notEndangered:

var animals: Set = ["Bison", "Mountain Gorilla", "Hedgehog", "Sea Turtle", "Vaquita", "Ocelet"] var notEndangered: Set = ["Bison", "Hedgehog", "Ocelet"]

We can use .subtracting() to create a set of animals that are endangered based on the two sets above:

var endangered = animals.subtracting(notEndangered)

If we were to output the value of endangered, we would get something similar to these results:

["Vaquita", "Mountain Gorilla", "Sea Turtle"]

Instructions

1.

Take a look at the sets foodEmojis and fruitEmojis in Emoji.swift.

Use the set operation .subtracting() to create a set called veggieEmojis that contains any element that is in the set foodEmojis but not in the set fruitEmojis.

Print the value of veggieEmojis.

Folder Icon

Take this course for free

Already have an account?