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

We now have everything we need to store a value in the hash table array. The only thing left is to assign the value at the index we calculated with the index(for:) function.

Storing and printing a value in a hash table should look something similar to:

someHashTable["Orange"] = "Fruit" print(someHashTable["Orange"]) // Prints: Fruit

To assign a value to an array using the above subscript format, we will first create an update(value:for:) method that will handle the logic needed to take a key-value pair from the subscript() function and store the value at a particular index.

Secondly, we will overload the subscript() function to assign a key-value pair.

Instructions

1.

Create a private mutating method, update(value:for:) that takes in two String parameters. The first parameter is named value and the second is key for accessing the key. The second parameter has an argument label for.

2.

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

3.

Set the value at the specified index to be value.

4.

Next, overload the public method subscript that takes in a String parameter called key. Since subscript will be a getter and setter for array values, have this method return an optional String.

5.

Inside your new subscript(key:) function, declare a setter and a getter. Inside the getter, return the empty String for now. This will get changed in a future exercise.

6.

Inside the setter, use an if let statement to ensure that the value is valid and not nil. If there is a valid value, call the update(value:for:) function on the value and the 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?