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
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
.
Inside your new function, create a constant elementIndex
assigned to calling your index(for:)
function on the key
parameter.
Set the value at the specified index to be value
.
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.
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.
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.