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.

Updated on: 09-May-2023

511 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements