title: Swift String removeSubrange - Protect from Index Error
body: <p>For a particular section of code, I have:</p>
  
  <pre><code>if let endIndex = lineEndIndex {
      buffer.removeSubrange(buffer.startIndex ..&lt; endIndex)
  }
  </code></pre>
  
  <p>Unfortunately, I am seeing the following error - <em>Fatal error: replaceSubrange: subrange extends past String end</em></p>
  
  <p>So, I need to guard against this condition with something like this:</p>
  
  <pre><code>if (buffer.endIndex &lt; lineEndIndex!) {
      lineEndIndex = buffer.endIndex
  }
  
  if let endIndex = lineEndIndex {
      buffer.removeSubrange(buffer.startIndex ..&lt; endIndex)
  }
  </code></pre>
  
  <p>However, this seems a bit 'kludgy'.  Is there a more elegant way to guard against trying to go outside the string's length with the <em>removeSubrange</em> function?</p>
  
  <p><strong>Update:</strong></p>
  
  <p>Based on Leo's second suggestion of using the <em>min</em> function, my chunk of code looks like this:</p>
  
  <pre><code>// unwrap lineEndIndex
  if let endIndex = lineEndIndex {
      // use the smaller of two values, buffer length or endIndex
      let endIndexVal = min(buffer.endIndex, endIndex)
  
      buffer.removeSubrange(buffer.startIndex ..&lt; endIndexVal)
  }
  </code></pre>