title: Fastest, leanest way to append characters to form a string in Swift
body: <p>I come from a C# background where <code>System.String</code> is immutable and string concatenation is relatively expensive (as it requires reallocating the string) we know to use the <code>StringBuilder</code> type instead as it preallocates a larger buffer where single characters (<code>Char</code>, a 16-bit value-type) and short strings can be concatenated cheaply without extra allocation.</p>
  
  <p>I'm porting some C# code to Swift which reads from a bit-array (<code>[Bool]</code>) at sub-octet indexes with character lengths less than 8 bits (it's a very space-conscious file format).</p>
  
  <p>My C# code does something like this:</p>
  
  <pre><code> StringBuilder sb = new StringBuilder( expectedCharacterCount );
   int idxInBits = 0;
   Boolean[] bits = ...;
   for(int i = 0; i &lt; someLength; i++) {
       Char c = ReadNextCharacter( ref idxInBits, 6 ); // each character is 6 bits in this example
       sb.Append( c );
   }
  </code></pre>
  
  <p>In Swift, I assume <code>NSMutableString</code> is the equivalent of .NET's <code>StringBuilder</code>, and I found this QA about appending individual characters ( <a href="https://stackoverflow.com/questions/25457615/how-to-append-a-character-to-string-in-swift">How to append a character to string in Swift?</a> ) so in Swift I have this:</p>
  
  <pre><code>var buffer: NSMutableString
  for i in 0..&lt;charCount {
      let charValue: Character = readNextCharacter( ... )
      buffer.AppendWithFormat("%c", charValue)
  }
  return String(buffer)
  </code></pre>
  
  <p>But I don't know why it goes through a format-string first, that seems inefficient (reparsing the format-string on every iteration) and as my code is running on iOS devices I want to be very conservative with my program's CPU and memory usage.</p>
  
  <p>As I was writing this, I learned my code should really be using <code>UnicodeScalar</code> instead of <code>Character</code>, problem is <code>NSMutableString</code> does not let you append a <code>UnicodeScalar</code> value, you have to use Swift's own mutable <code>String</code> type, so now my code looks like:</p>
  
  <pre><code>var buffer: String
  for i in 0..&lt;charCount {
      let x: UnicodeScalar = readNextCharacter( ... )
      buffer.append(x)
  }
  return buffer
  </code></pre>
  
  <p>I thought that <code>String</code> was immutable, but I noticed its <code>append</code> method returns <code>Void</code>.</p>
  
  <p>I still feel uncomfortable doing this because I don't know how Swift's <code>String</code> type is implemented internally, and I don't see how I can preallocate a large buffer to avoid reallocations (assuming Swift's <code>String</code> uses a growing algorithm).</p>