title: Swift UTF16 Substring
body: <p>I'm receiving a string from the server in the following format:</p>
  
  <p><code>118|...message...215|...message2...</code></p>
  
  <p>Basically, it's the message <em>length</em> followed by a pipe and the message itself, repeated for multiple messages.  The message is encoded UTF16.</p>
  
  <p>I'm looking for a way to parse this in Swift.  I know I could cast this as <code>NSString</code> and use standard indexes/ranges on that because UTF16 is what NSString uses, but I'm wondering what is the <em>Swift</em> way to handle this? I can't seem to find a way to pull a substring out of a <code>String</code> based on a UTF16 encoding.  </p>
  
  <h3>Update</h3>
  
  <p>I'm not trying to <em>initialize</em> a <code>String</code> with raw UTF16 Data (there's plenty of ways to do that).  I already have the string, so I'm trying to take a <code>String</code> in the above format and parse it.  The issue I have is that the message length given to me by the server is based on UTF16.  I can't simply extract the length and call <code>String.advance(messageLength)</code> on the Index because the length I've been given doesn't match the grapheme clusters that Swift advances on.  My issue is that I can't extract from the string the message in Swift.  I have to instead cast it over to <code>NSString</code> and then use "normal" <code>NSRange</code> on it.  My question is how do I pull the substring out by extracting a range based on my <em>search</em> for the first pipe, and then use the length provided by the parser in UTF16.  </p>
  
  <p>This is all extremely simple to do with <code>NSString</code>.  Not sure how it can be done in pure Swift (or if it can be done).</p>