title: Safe (bounds-checked) array lookup in Swift, through optional bindings?
body: <p>If I have an array in Swift, and try to access an index that is out of bounds, there is an unsurprising runtime error:</p>
  
  <pre><code>var str = ["Apple", "Banana", "Coconut"]
  
  str[0] // "Apple"
  str[3] // EXC_BAD_INSTRUCTION
  </code></pre>
  
  <p>However, I would have thought with all the optional chaining and <em>safety</em> that Swift brings, it would be trivial to do something like:</p>
  
  <pre><code>let theIndex = 3
  if let nonexistent = str[theIndex] { // Bounds check + Lookup
      print(nonexistent)
      ...do other things with nonexistent...
  }
  </code></pre>
  
  <p>Instead of:</p>
  
  <pre><code>let theIndex = 3
  if (theIndex &lt; str.count) {         // Bounds check
      let nonexistent = str[theIndex] // Lookup
      print(nonexistent)   
      ...do other things with nonexistent... 
  }
  </code></pre>
  
  <p>But this is not the case - I have to use the ol' <code>if</code> statement to check and ensure the index is less than <code>str.count</code>.</p>
  
  <p>I tried adding my own <code>subscript()</code> implementation, but I'm not sure how to pass the call to the original implementation, or to access the items (index-based) without using subscript notation:</p>
  
  <pre><code>extension Array {
      subscript(var index: Int) -&gt; AnyObject? {
          if index &gt;= self.count {
              NSLog("Womp!")
              return nil
          }
          return ... // What?
      }
  }
  </code></pre>