title: Read a file/URL line-by-line in Swift
body: <p>I am trying to read a file given in an <code>NSURL</code> and load it into an array, with items separated  by a newline character <code>\n</code>. </p>
  
  <p>Here is the way I've done it so far:</p>
  
  <pre><code>var possList: NSString? = NSString.stringWithContentsOfURL(filePath.URL) as? NSString
  if var list = possList {
      list = list.componentsSeparatedByString("\n") as NSString[]
      return list
  }
  else {
      //return empty list
  }
  </code></pre>
  
  <p>I'm not very happy with this for a couple of reasons. One, I'm working with files that range from a few kilobytes to hundreds of MB in size. As you can imagine, working with strings this large is slow and unwieldy. Secondly, this freezes up the UI when it's executing--again, not good.</p>
  
  <p>I've looked into running this code in a separate thread, but I've been having trouble with that, and besides, it still doesn't solve the problem of dealing with huge strings.</p>
  
  <p>What I'd like to do is something along the lines of the following pseudocode:</p>
  
  <pre><code>var aStreamReader = new StreamReader(from_file_or_url)
  while aStreamReader.hasNextLine == true {
      currentline = aStreamReader.nextLine()
      list.addItem(currentline)
  }
  </code></pre>
  
  <p><strong>How would I accomplish this in Swift?</strong></p>
  
  <p><em>A few notes about the files I'm reading from:</em> All files consist of short (&lt;255 chars) strings separated by either <code>\n</code> or <code>\r\n</code>. The length of the files range from ~100 lines to over 50 million lines. They may contain European characters, and/or characters with accents.</p>