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:


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:


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

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



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


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.

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?