The least you need to know about hashing in Swift

06609d73ad2165c4aafcf65a1ddb9563?s=47 Greg Heo
August 15, 2018

The least you need to know about hashing in Swift

Including Swift 4.2! Hashable, hash values, and how to calculate your hash values.

Presented at the Swift Language User Group, August 2018.

06609d73ad2165c4aafcf65a1ddb9563?s=128

Greg Heo

August 15, 2018
Tweet

Transcript

  1. 1.

    @gregheo SLUG August 2018 Everything The least you need to

    know about hashing in Swift (including Swift 4.2!) @gregheo {
  2. 4.

    @gregheo SLUG August 2018 What is a hash? What are

    hash values used for? How do I calculate good hash values?
  3. 22.

    @gregheo SLUG August 2018 extension Puppy: Hashable { var hashValue:

    Int { return Int(arc4random_uniform(1000))
 } }
  4. 24.

    @gregheo SLUG August 2018 struct Puppy: Hashable { let name:

    String let age: Int
 } struct RedPanda: Hashable { let name: String let sequence: Int
 }
  5. 25.

    @gregheo SLUG August 2018 let p1 = Puppy(name: "Boba", age:

    8)
 let p2 = RedPanda(name: "Boba", sequence: 8)
 p1.hashValue p2.hashValue // 7824938159186139988 // 7824938159186139988
  6. 26.

    @gregheo SLUG August 2018 var hashValue: Int { return age.hashValue

    ^
 name.hashValue ^ “Puppy”.hashValue
 }
  7. 27.

    @gregheo SLUG August 2018 func hash(into hasher: inout Hasher) {

    hasher.combine(age) hasher.combine(name) } N E W !
  8. 29.

    @gregheo SLUG August 2018 What is a hash? What are

    hash values used for? How do I calculate good hash values?