Swift Dictionary removeValue()

The removeValue() method removes the certain key and its associated value from the dictionary.

Example

// create a dictionary with two elements
var information = ["Charlie": 54, "Harvey": 34]

// remove certain key-value pair using removeValue() information.removeValue(forKey: "Charlie")
// print updated dictionary print(information) // Output: ["Harvey": 34]

removeValue() Syntax

The syntax of the removeValue() method is:

dictionary.removeValue(forKey: key)

Here, dictionary is an object of the Dictionary class.


removeValue() Parameters

The removeValue() method takes one parameter:

  • key - The key to remove along with its associated value.

removeValue() Return Value

  • The removeValue() method returns the removed value from dictionary.

Example: Swift removeValue()

// create a dictionary with three elements
var numbers = ["one": 1, "Two": 2, "Three": 3]

print("Before:", numbers)

// remove "Three" and it's associated value 3 numbers.removeValue(forKey: "Three")
// print updated dictionary print("After:", numbers)

Output

Before: ["Two": 2, "one": 1, "Three": 3]
After: ["Two": 2, "one": 1]

In the above example, we have created a dictionary named numbers with three key-value pairs.

Here, we have used the removeValue() method to remove the key named "Three" and its associated value 3.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges