Learn
Sets
Removing Elements

If we need to remove an element from a set, we can use .remove().

This method can remove a single item from a set with the following syntax:

setName.remove(Value)

Let’s revisit the set plantShelf from the previous exercise:

var plantShelf: Set = ["Haworthia", "Graptopetalum", "Echeveria", "Corpuscularia"]

Unfortunately, we overwatered the "Haworthia" plant, and it wilted away.

To remove this value from plantShelf using .remove(), we can use this code:

plantShelf.remove("Haworthia")

If we tried to remove a value that didn’t exist within the set plantShelf, like "Astridia", the set would be unaffected.

If we wanted to remove every single element from a set, we could use the .removeAll() method:

setName.removeAll()

Let’s say we are moving our plant collection over to the window sill. Removing all the values from plantShelf looks like this:

plantShelf.removeAll()

If we print the value of plantShelf after removing all the values, the output looks like this:

[]

Instructions

1.

Take a look at the set in Planets.swift. Since "Pluto" is no longer considered a planet, we should remove it from our set.

Remove the value "Pluto" from the set planets using .remove().

Print the value of planets.

2.

We have entered the Andromeda Galaxy!

Remove all the values from planets using .removeAll().

Print the value of planets again.

Folder Icon

Take this course for free

Already have an account?