Now that we can assign elements to the hash table, we have to be able to retrieve the values we are storing. Retrieving an element should look something like:
// Assignment someHashTable["Name"] = "John" // Retrieval print(someHashTable["Name"]) // Prints: John
To retrieve a value from a hash table, we’ll create a private method value(for:)
to return a value from the array. It will first calculate the index of the key-value pair you desire using the index(for:)
function and return the value at the calculated index.
Next, let’s call and return value(for:)
inside of subscript(key:)
‘s getter function. This will return the value at the desired index when retrieving it similar to the example above.
Instructions
Create a private method, value(for:)
that takes in a key
String parameter with an argument label of for
.
Inside your new method, create a new constant elementIndex
equal to the index(for:)
function called on the key
parameter.
Return the value located at the calculated index.
Inside the subscript
method getter, return the function call to value(for:)
with the accessed key.