title: Accessing Swift set elements by their hash value
body: <p>Say I'm making a chess app, in which a position is stored like this:</p>
  
  <pre><code>struct Position {
      var pieces: Set&lt;Piece&gt;
      // some other stuff
  }
  </code></pre>
  
  <p><code>Piece</code> is defined as follows:</p>
  
  <pre><code>struct Piece: Hashable {
      var row: Int
      var column: Int
      let player: Player
      let type: PieceType
  
      var hashValue: Int {
          return 8 * row + column
      }
  }
  </code></pre>
  
  <p><code>Player</code> and <code>PieceType</code> are simple enums:</p>
  
  <pre><code>enum Player {
      case White, Black
  }
  
  enum PieceType {
      case Queen, King, ...
  }
  </code></pre>
  
  <p>Now, I would like to access a <code>Piece</code> in a <code>Position</code> by its position on the board. The hash value of a <code>Piece</code> is uniquely determined by its position, so access to a <code>Piece</code> should be possible in constant time. However, a Swift set doesn't have a function to get one of its elements by its hash value. All I could come up with is</p>
  
  <pre><code>for piece in pieces {
      if piece.hashValue == 25 {
          // do something
      }
  }
  </code></pre>
  
  <p>...but obviously, this runs in linear time, not in constant time.</p>
  
  <p>A way to solve this problem is to not use a set, but an array instead:</p>
  
  <pre><code>var pieces: [Piece?]
  </code></pre>
  
  <p>Then I can access the piece at a certain position simply with <code>pieces[25]</code>, in constant time. I do find this less elegant, because this method stores the position of each <code>Piece</code> twice: by the position in the <code>pieces</code> array and by the values of the <code>row</code> and <code>column</code> variables.</p>
  
  <p>Is there a way to access a set element by its hash value (in constant time)? Or should I just use an array?</p>