title: How does Dictionary use the Equatable protocol in Swift?
body: <p>In order to solve <a href="https://stackoverflow.com/questions/31664159/how-to-handle-hash-collisions-for-dictionaries-in-swift">this question</a>, I have been playing around with a custom struct that implements the Hashable Protocol. I'm trying to see how many times the equivalency operator overload (<code>==</code>) gets called depending on if there is a hash collision or not when populating a <code>Dictionary</code>.</p>
  
  <p><strong>Update</strong></p>
  
  <p><a href="https://stackoverflow.com/users/341994/matt">@matt</a> wrote a much cleaner example of a custom struct that implements the Hashable protocol and shows how often <code>hashValue</code> and <code>==</code> get called. I am copying <a href="https://gist.github.com/mattneub/430fef70e3496f5ce6917aa35c98f419" rel="noreferrer">his code</a> below. To see my original example, check out the <a href="https://stackoverflow.com/posts/31665802/revisions">edit history</a>.</p>
  
  <pre><code>struct S : Hashable {
      static func ==(lhs:S,rhs:S) -&gt; Bool {
          print("called == for", lhs.id, rhs.id)
          return lhs.id == rhs.id
      }
      let id : Int
      var hashValue : Int {
          print("called hashValue for", self.id)
          return self.id
      }
      init(_ id:Int) {self.id = id}
  }
  var s = Set&lt;S&gt;()
  for i in 1...5 {
      print("inserting", i)
      s.insert(S(i))
  }
  </code></pre>
  
  <p>This produces the results:</p>
  
  <pre><code>/*
  inserting 1
  called hashValue for 1
  inserting 2
  called hashValue for 2
  called == for 1 2
  called hashValue for 1
  called hashValue for 2
  inserting 3
  called hashValue for 3
  inserting 4
  called hashValue for 4
  called == for 3 4
  called == for 1 4
  called hashValue for 2
  called hashValue for 3
  called hashValue for 1
  called hashValue for 4
  called == for 3 4
  called == for 1 4
  inserting 5
  called hashValue for 5
  */
  </code></pre>
  
  <p>Since Hashable uses Equatable to differentiate hash collisions (I assume anyway), I would expect <code>func ==()</code> only to be called when there are hash collisions. However, there are no hash collisions at all in @matt's example above and yet <code>==</code> is still being called. In my other experiments forcing hash collisions (see this question's edit history), <code>==</code> seemed to be called a random number of times.</p>
  
  <p>What is going on here?</p>