Learn
Sets
Inserting Elements

If we want to add new elements to our set, we can use Swift’s built-in .insert() method.

Being able to augment our sets with new elements is useful when we have additional data to store or when we are ready to populate an empty set.

We can use .insert() to add elements to a set using this syntax:

setName.insert(NewValue)

When appending elements to a set:

  • The set we are adding to must already exist.
  • The new value must be the same data type that the set was initialized with.
  • If we try to add an item that already exists, the item will still only appear once in the set.

Imagine we have a collection of plants:

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

After walking through a plant nursery, we are now the proud owners of a "Graptopetalum". To reflect this change in our set, we can use the following code:

plantShelf.insert("Graptopetalum")

If we tried to print this set, our output will look like some variation of this:

["Haworthia", "Graptopetalum", "Echeveria", "Corpuscularia"]

Instructions

1.

Add the value "Hermione" to the set friends using .insert().

2.

Add the value "Ron" to the set friends using .insert().

Notice that, when we run this code, "Ron" is only printed once even though we inserted the value for a second time.

Folder Icon

Take this course for free

Already have an account?