We can use .remove()
to remove or delete an element from a set in Swift.
With the following syntax, this function can delete a single item from a set:
setName.remove(Value)
Let’s go back to the prior exercise’s set Library
:
var Library: Set = ["Caraval", "Speak", "Cinder", "Insurgent"];
Unfortunately, we misplaced the "Caraval"
book, and it is no longer available. We may use the following code to delete this value from the Library
using .remove()
:
Library.remove("Caraval");
If we tried to delete a value from the set Library
that didn’t exist, such as "Divergent"
, the set would be unaffected.
We may use the .removeAll()
function to remove every single element from a set. The syntax for it is as follows:
setName.removeAll()
Assume we are relocating our book collection. Removing all of the values from Library
looks like this:
Library.removeAll();
If we print the value of Library after removing all the values, we get the following:
[]
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.