Pro Yearly is on sale from $80 to $50! »

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. @gregheo SLUG August 2018 Everything The least you need to

    know about hashing in Swift (including Swift 4.2!) @gregheo {
  2. @gregheo SLUG August 2018 extension Puppy { }

  3. @gregheo SLUG August 2018 extension Puppy: Hashable { } {

    return 0 } var hashValue: Int
  4. @gregheo SLUG August 2018 What is a hash? What are

    hash values used for? How do I calculate good hash values?
  5. @gregheo SLUG August 2018 0 1 2 3 4 5

    6 7 8 9 …
  6. @gregheo SLUG August 2018 0 1 2 3 4 5

    6 7 8 9 …
  7. @gregheo SLUG August 2018

  8. @gregheo SLUG August 2018

  9. @gregheo SLUG August 2018 var hashValue: Int

  10. @gregheo SLUG August 2018 Int data hash function

  11. @gregheo SLUG August 2018 == hash hash == *

  12. @gregheo SLUG August 2018 != hash hash != hash hash

    == possible!
  13. @gregheo SLUG August 2018 Int data hash function

  14. @gregheo SLUG August 2018 Int data hash function

  15. @gregheo SLUG August 2018 != hash hash !=

  16. @gregheo SLUG August 2018 hash hash == ==

  17. @gregheo SLUG August 2018 == hash hash == hash hash

    != !=
  18. @gregheo SLUG August 2018 extension Puppy: Hashable { } {

    return 0 } var hashValue: Int
  19. @gregheo SLUG August 2018

  20. @gregheo SLUG August 2018 0 1 2 3 4 5

    6 7 8 9 …
  21. @gregheo SLUG August 2018 extension Puppy: Hashable { var hashValue:

    Int {
 return 0
 } }
  22. @gregheo SLUG August 2018 extension Puppy: Hashable { var hashValue:

    Int { return Int(arc4random_uniform(1000))
 } }
  23. @gregheo SLUG August 2018 var hashValue: Int { return age.hashValue

    ^ name.hashValue
 }
  24. @gregheo SLUG August 2018 struct Puppy: Hashable { let name:

    String let age: Int
 } struct RedPanda: Hashable { let name: String let sequence: Int
 }
  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
  26. @gregheo SLUG August 2018 var hashValue: Int { return age.hashValue

    ^
 name.hashValue ^ “Puppy”.hashValue
 }
  27. @gregheo SLUG August 2018 func hash(into hasher: inout Hasher) {

    hasher.combine(age) hasher.combine(name) } N E W !
  28. @gregheo SLUG August 2018 struct Puppy: Hashable { let name:

    String let age: Int
 }
  29. @gregheo SLUG August 2018 What is a hash? What are

    hash values used for? How do I calculate good hash values?
  30. @gregheo SLUG August 2018 swiftunboxed.com/protocols/hashable/ }