Log in from a computer to take this course

You'll need to log in from a computer to start Introduction to Algorithms and Linear Data Structures in Swift. But you can practice or keep up your coding streak with the Codecademy Go app. Download the app to get started.

apple storegoogle store
Learn

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.

Instructions

1.

Create a private mutating method, removeValue that takes in a key String parameter with an argument label of for.

2.

Inside your new method, create a new constant elementIndex equal to the index(for:) function called on the key parameter.

3.

Set the value at the index of the array equal to the empty String.

4.

Inside the subscript method setter, if the value is nil, then call the function removeValue(for:) on the provided key.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?