title: Histogram of Array in Swift
body: <p>I'm trying to write a generic histogram function that operates on an <code>Array</code>, but I'm running into difficulties as <strong>Type 'Element' does not conform to protocol 'Hashable'</strong>.</p>
  
  <pre><code>extension Array {
      func histogram() -&gt; [Array.Element: Int] {
          return self.reduce([Array.Element: Int]()) { (acc, key) in
                  let value = (acc[key] == nil) ? 1 : (acc[key]! + 1)
                  return acc.dictionaryByUpdatingKey(key: key, value: value)
          }
      }
  }
  </code></pre>
  
  <p>where <code>dictionaryByUpdatingKey(...)</code> mutates an existing dictionary as follows:</p>
  
  <pre><code>extension Dictionary {
      func dictionaryByUpdatingKey(key: Dictionary.Key, value: Dictionary.Value) -&gt; Dictionary {
          var mutableSelf = self
          let _ = mutableSelf.updateValue(value, forKey: key)
          return mutableSelf
      }
  }
  </code></pre>
  
  <p>I have tried replacing <code>Array.Element</code> with <code>AnyHashable</code> and then forcing the <code>key as! AnyHashable</code>, but this seems messy and the return type should preferably be of the same type as the <code>Array.Element</code> and not of <code>AnyHashable</code>.</p>
  
  <p>I wish to use the <code>Array</code> extension as follows:</p>
  
  <pre><code>let names = ["Alex", "Alex", "James"]
  print(names.histogram()) // ["James": 1, "Alex": 2]
  </code></pre>
  
  <p>or</p>
  
  <pre><code>let numbers = [2.0, 2.0, 3.0]
  print(numbers.histogram()) // [3.0: 1, 2.0: 2]
  </code></pre>