The last operation we need our
HashTable to allow is deleting elements. Deleting an element would look something like:
someeHashTable["Orange"] = "Orange" print(someHashTable["Orange"] // Prints: Orange someHashTable["Orange"] = nil print(someHashTable["Orange"] // Prints: ""
To delete a value from the array, we will first create a
removeValue(for:) method to delete the value from the array. In the example above, notice that the value is the empty String, not
nil. Since the array needs to stay the same size, deleting an element actually means setting the value to the empty String instead of removing the element from the array.
Secondly, we will modify the
subscript(key:) function’s setter to remove the value if the value provided is equal to
nil. That is, if no value is actually provided, we will call the
removeValue(for:) function on the provided key.
Create a private
removeValue that takes in a
key String parameter with an argument label of
Inside your new method, create a new constant
elementIndex equal to the
index(for:) function called on the
Set the value at the index of the array equal to the empty String.
subscript method setter, if the value is
nil, then call the function
removeValue(for:) on the provided key.