Removing an item from a dictionary

To remove an item from a dictionary, assign nil to an existing key. Type in and run the following code:

// Removing "Kajal" from the dictionary
contactList["Kajal"] = nil
contactList

contactList now consists of "Shah" : "+60126789345" and "Akhil" : "+0223456789". You can see this in the Results area.

If you want to assign the value you are removing to a variable or constant, use removeValue(for:Key) instead. Modify your code as follows:

// Removing "Kajal" from the dictionary
var oldDictValue = contactList.removeValue(forKey: "Kajal")
oldDictValue
contactList

oldDictValue ("+0229876543") and contactList ("Shah" : "+60126789345" and "Akhil" : "+0223456789") are displayed in the Results area.

Finally, let's look at how to iterate over a dictionary.

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

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