Kodeco Forums

Swift Algorithm Club: Hash Tables

Learn how to implement a hash table data structure in Swift, in this step-by-step tutorial from the Swift Algorithm Club.

This is a companion discussion topic for the original entry at https://www.raywenderlich.com/206-swift-algorithm-club-hash-tables

Hi, Kelvin.

Thanks for the article, great explanation of what is the essence of HashTable.

I found a small type in your code:

public func value(for key: Key) -> Value? {
  let index = self.index(for: key)
  return buckets[index].first { $0.key == key }?.value

There should be filter instead of first.

You’re welcome!

Could you elaborate on why filter would work better? filter returns an array of elements matching the closure logic, and first is essentially a filter that stops when it finds the first match.

Sorry, my bad!

I didn’t know that an array has first API method.

Hi Kelvin,
i Am particularly interested in this function

func djb2Hash(_ string: String) β†’ Int {
let unicodeScalars = string.unicodeScalars.map { $0.value }
return unicodeScalars.reduce(5381) {
($0 << 5) &+ $0 &+ Int($1)

I am calling djb@Hash(β€œa”)
so here $0 = 5381 and $1 = 97 (unicode value of β€œa”)

My question is how we are getting the value $1 inside the .reduce?

reduce takes a closure with two parameters. $0 references the first parameter, while $1 references the second parameter.

In this context, $1 refers a particular character of the String during a particular iterative step.

This tutorial is more than six months old so questions are no longer supported at the moment for it. Thank you!