Removing a key-value pair

There may be times when we need to remove values from a dictionary. There are three ways to achieve this: using the subscript syntax, the removeValue(forKey:) method, and the removeAll() method. The removeValue(forKey:) method returns the value of the key prior to removing it. The removeAll() method removes all the elements from the dictionary. The following example shows how to use all three methods to remove key-value pairs from a dictionary:

var countries = ["US":"UnitedStates","IN":"India","UK":"United Kingdom"]; 
countries["IN"] = nil //The "IN" key/value pair is removed  
var orig = countries.removeValue(forKey:"UK") 
//The "UK" key value pair is removed and orig contains "United Kingdom" 
 
countries.removeAll() 
//Removes all key/value pairs from the countries dictionary

In the preceding code, the countries dictionary starts off with three key-value pairs. We then set the value associated with the key IN to nil, which removes the key-value pair from the dictionary. We use the removeValue(forKey:) method to remove the key associated with the UK key. Prior to removing the value associated with the UK key, the removeValue(forKey:) method saves the value in the orig variable. Finally, we use the removeAll() method to remove all the remaining key-value pairs in the countries dictionary.

Now let's look at the set type.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset