title: Swift String rare crash
body: <p>In my app I have a logger that writes errors and status messages to a string. It's not written to a file, it's just handy to have something to look at when a bug happens without an attached debug session.</p>
  <p>The addLog() method is called approx. 0-10 times every 3 seconds and is fairly simple:</p>
  <ul>
  <li>every call adds the new addition to the beginning of the string along with the second it has happened</li>
  <li>to prevent the string from blowing up in terms of size, if it exceeds 2kb, it will successively cut the &quot;oldest&quot; 100 log characters until it's smaller than 2kb again</li>
  </ul>
  <p>The code looks as following:</p>
  <pre><code>var logString = &quot;&quot;
  
  func addLog(s : String){
      let date = Date()
      
      logString =  &quot;\(date.second)\(s).\n\(logString)&quot;
      
      while(logString.count&gt;2000){
          logString=String(logString.dropLast(100))
      }
  }
  </code></pre>
  <p>I've never seen anything wrong with it until today when I received a crash log:</p>
  <pre><code>Thread 5 name:
  Thread 5 Crashed:
  0   libsystem_kernel.dylib          0x00000001c00f5414 __pthread_kill + 8
  1   libsystem_pthread.dylib         0x00000001ddc50b50 pthread_kill + 272 (pthread.c:1392)
  2   libsystem_c.dylib               0x000000019b5d3b74 abort + 104 (abort.c:110)
  3   libsystem_malloc.dylib          0x00000001a1faf49c malloc_vreport + 560 (malloc_printf.c:183)
  4   libsystem_malloc.dylib          0x00000001a1faf740 malloc_zone_error + 104 (malloc_printf.c:219)
  5   libsystem_malloc.dylib          0x00000001a1f99ed8 free_small_botch + 40 (magazine_small.c:2215)
  6   libswiftCore.dylib              0x00000001961103d8 _swift_release_dealloc + 40 (HeapObject.cpp:648)
  7   APPNAME                         0x00000001046b56a0 AppDelegate.addLog(s:) + 960 (AppDelegate.swift:0)
  </code></pre>
  <p>What's weird about the log itself is that the <code>addLog()</code> function is not in line 0 of my AppDelegate but maybe that's normal to have the wrong line in the crash report.</p>
  <p>The only possible explanation for this issue that I can come up with is that there is an issue with thread safety in my function, or that I have missed something regarding the garbage collection in swift. It's very likely that the function is called from different threads at the same time, could that be an issue? Or do I have to get into the objective-c times <code>retain</code> etc. again to resolve this? What can I make out of this crash log?</p>