Swift: Inserting Elements

Inserting Elements in Swift’s Set:

We can use Swift’s built-in .insert() method to insert elements to our set in Swift. The ability to add new elements is useful when we have additional data to store in set.

Using the following syntax, we can use .insert() to add elements to a set:

setName.insert(NewValue)

When adding elements to a set:

  • The set to which we are adding must already exist.
  • The new value must be of the same data type as the set’s initialization.
  • If we try to add an already existing item, it will only appear once in the set.

Imagine we have a collection of Books:

var Library: Set = ["Cinder", "Caraval", "Speak"];

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

Library.insert("Insurgent");

Printing this set will give the following result:

["Caraval", "Speak", "Cinder", "Insurgent"]

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: