O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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() ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required