title: How can I properly guard a substring function in Swift 3?
body: <p>I have two similar functions to get a substring of a string in swift (I only need one):</p>
  
  <pre><code>func substring(start: Int, end: Int) -&gt; String {
      let c = self.characters
      let r = c.index(c.startIndex, offsetBy: start)..&lt;c.index(c.startIndex, offsetBy: end)
      let substring = self[r]
      return substring
  }
  </code></pre>
  
  <p>and:</p>
  
  <pre><code>func substring(start: Int, end: Int) -&gt; String {
      let startIndex = self.index(self.startIndex, offsetBy: start)
      let endIndex = self.index(self.startIndex, offsetBy: end)      
      return self[startIndex..&lt;endIndex]
  }
  </code></pre>
  
  <p>How can I properly guard this? Here is the main error I can get here:</p>
  
  <blockquote>
    <p>fatal error: cannot decrement before startIndex</p>
  </blockquote>
  
  <p>I need to be able to send in all types of bad values into this function, such as negative <code>start</code>s and <code>end</code>s or <code>end</code>s that are less than <code>start</code>s. For the purpose of learning, let's assume there is a good reason to allow nonsense parameters in the function.</p>
  
  <p>I have tried a few things, like:</p>
  
  <pre><code>func substring(start: Int, end: Int) -&gt; String {
      guard end &gt; 0 else {
          return "something"
      }
  
      let startIndex = self.index(self.startIndex, offsetBy: start)
      let endIndex = self.index(self.startIndex, offsetBy: end)      
      return self[startIndex..&lt;endIndex]
  }
  </code></pre>
  
  <p>but these either don't work or cause my app to freeze.</p>