title: subscripts and protocols in swift
body: <p>I am defining a Protocol, for abstraction purposes, having a "subscript" function with both a getter and a setter.
  Then I am defining a class implementing that protocol.</p>
  
  <p>Short version of the problem: if I use the subscript on an object of the class (as an lvalue, and thus using the setter), everything works as expected. If I do it on an object just declared of the protocol type, I get a "Cannot assign to the result of this expression" error.</p>
  
  <p>Long version.
  I have a board of Int. A board is a 2D matrix. I expose the Board type via the BoardType protocol.</p>
  
  <pre><code>protocol BoardType {
      var width: Int { get }
      var height: Int { get }
      subscript(x: Int, y: Int) -&gt; Int { get set }
  }
  
  class Board: BoardType {
  
      let width, height: Int
      var matrix: Array2D&lt;Int&gt;
  
      init(width: Int, height: Int) {
          self.width = width
          self.height = height
          matrix = Array2D&lt;Int&gt;(cols: width, rows: height, defaultValue: 0)
      }
  
      subscript(x: Int, y: Int) -&gt; Int {
          get {
              return matrix[x, y]
          }
          set {
              matrix[x, y] = newValue
          }
      }
  }
  </code></pre>
  
  <p>The implementation of Array2D is standard:</p>
  
  <pre><code>class Array2D&lt;T&gt; {
  
      var cols: Int, rows: Int
      var matrix: [T]
  
      init(cols: Int, rows:Int, defaultValue: T) {
          self.cols = cols
          self.rows = rows
          matrix = Array(count: cols*rows, repeatedValue: defaultValue)
      }
  
      subscript(x: Int, y: Int) -&gt; T {
          get {
              return matrix[cols * y + x]
          }
          set {
              matrix[cols * y + x] = newValue
          }
      }
  
      func colCount() -&gt; Int {
          return self.cols
      }
  
      func rowCount() -&gt; Int {
          return self.rows
      }
  }
  </code></pre>
  
  <p>Now, if I do the following, it works:</p>
  
  <pre><code>    let board = Board(width: 4, height: 4)
      board[1, 1] = 10
  </code></pre>
  
  <p>Instead, if I use the prototype, I get the error</p>
  
  <pre><code>    let board : BoardType = Board(width: 4, height: 4)
      board[1, 1] = 10
  </code></pre>
  
  <p>Why?</p>