- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Swift Program to Remove an Element from a Dictionary
In Swift, we can remove an element from the specified dictionary using the removeValue() function. This function removes the specified key and its associated value from the given dictionary.
Syntax
Dict.removeValue(forKey: key)
Here, the key represents the key which we wanted to remove from the dictionary along with its value, and the dict represents the dictionary.
Algorithm
Step 1 − Create a dictionary with key-value pairs.
Step 2 − Print the original dictionary.
Step 3 − Remove a key-value pair whose key is 2 using the removeValue() function.
Step 4 − Print the updated dictionary.
Example
In the following Swift program, we will remove an element from a dictionary. So to do this we will create a dictionary with key-value pairs. Then we use the removeValue() function to remove key = 2 along with its value from the given dictionary. Finally, we display the modified dictionary.
import Foundation import Glibc // Creating a dictionary var dict = [3: "apple", 4: "banana", 19: "orange", 2: "grapes", 87: "mango"] print("Original Dictionary:", dict) // Removing a key-Value pair dict.removeValue(forKey: 2) // Displaying output print("Updated Dictionary:", dict)
Output
Original Dictionary: [87: "mango", 19: "orange", 2: "grapes", 4: "banana", 3: "apple"] Updated Dictionary: [87: "mango", 19: "orange", 4: "banana", 3: "apple"]
Conclusion
So this is how we can remove an element from a dictionary. Here the removeValue() method removes one key at a time. Also if the specified key does not present in the given dictionary, then it will return nil.