title: UTF8 String length and indices in Go vs Swift
body: <p>I have apps in Go and Swift which process strings, such as finding substrings and their indices. At first it worked nicely even with multi-byte characters (e.g. emojis), using to Go's <code>utf8.RuneCountInString()</code> and Swift's native String.</p>
  
  <p>But there are some UTF8 characters that break the string length and indices for substrings, e.g. a string <code>"Lorem ✌️ ipsum"</code>:</p>
  
  <p>Go's <code>utf8.RuneCountInString("Lorem ✌️ ipsum")</code> returns 17 and the start index of <code>ipsum</code> is 12.</p>
  
  <p>Swift's <code>"Lorem ✌️ ipsum".count</code> returns 16 and the start index of <code>ipsum</code> is 11.</p>
  
  <p>Using Swift String's <code>utf8</code>, <code>utf16</code> or casting to <code>NSString</code> gives also different lengths and indices. There are also other emojis composed from multiple other emoji's like ‍‍‍ which gives even funnier numbers.</p>
  
  <p>This is with Go 1.8 and Swift 4.1.</p>
  
  <p>Is there any way to get the same string lengths and substrings' indices with same values with Go and Swift?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I created a Swift String extension based on @MartinR's great answer:</p>
  
  <pre><code>extension String {
      func runesRangeToNSRange(from: Int, to: Int) -&gt; NSRange {
          let length = to - from
          let start = unicodeScalars.index(unicodeScalars.startIndex, offsetBy: from)
          let end = unicodeScalars.index(start, offsetBy: length)
          let range = start..&lt;end
  
          return NSRange(range, in: self)
      }
  }
  </code></pre>