Swift: Removing Elements

Removing Elements of Swift’s Dictionary:

When it comes to removing key-value pairs or elements from a Swift dictionary, you have a few options.

The keyword nil in Swift denotes something that is empty or has no value. The key-value pair would be removed from the dictionary if the value of a key was set to nil:

dictionaryName[Key] = nil

Consider the dictionary library, which keeps track of key-value pairs of titles and authors for books we currently own:

var library = [
  "Ulysses": "James Joyce",
  "Don Quixote": "Miguel de Cervantes",
  "War and Peace": "Leo Tolstoy"
];

Consider participating in a book drive and donating one of the books collected. Let’s remove the key-value pair "Ulysses": "James Joyce" from library by setting the value of "Ulysses" to nil:

library["Ulysses"] = nil;

The .removeValue() method can also be used to remove a single key-value pair:

nameofDictionary.removeValue(forKey: Key)

After forKey:, the .removeValue() method takes a key name to determine which key-value pair to remove.

If we were to delete an element from the library using the .removeValue() method, our code would look like this:

library.removeValue(forKey: "Ulysses");

We could use the .removeAll() method to delete every key-value pair in a dictionary at once:

nameofDictionary.removeAll()

It’s worth noting that this method requires no input; simply append .removeAll() to an existing dictionary.

If we needed to remove all of the values from library, we would use the following syntax:

library.removeAll();

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: