Removing dictionary elements

We can remove an element from a dictionary by setting its value to nil:

dict["three"] = nil 

If we need to retrieve the old value as well, we can use the removeValue method:

let val = dict .removeValue(forKey: "three") 

If we need to remove dictionary elements one at a time in no particular order, and have their values returned, we can use the popFirst method:

let poppedElement = dict.popFirst() 

In this case, the dict dictionary had been mutated, and poppedElement now contains either the value of the key/value pair, or nil if the dictionary was empty.

We can remove all elements from a dictionary using either of these two methods:

dict.removeAll() 
dict = [:]