0

I have this function for hashing:

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

djb2Hash("abc") // outputs 193485963
djb2Hash("bca") // outputs 193487083

I don't understand why the author used reduce(5381) and don't really get the code from the closure that comes next. Can someone explain.

Thanks

Shum
  • 23
  • 5
  • 1
    Does [this](https://stackoverflow.com/q/10696223/5133585) answer your question? You can also see a C implementation of the same algorithm, which should explain a lot. – Sweeper Aug 29 '22 at 10:12
  • See also [this](https://stackoverflow.com/q/35472685/5133585) if you don't understand what `&+` means, and [this](https://stackoverflow.com/q/72424588/5133585) if you don't understand `reduce`. – Sweeper Aug 29 '22 at 10:16

0 Answers0