title: Load numeric array from text file in Swift
body: <p>I'm using a Swift function that successfully loads data from a text file into an <code>Double</code> array, but it is slow. Is there a way to load numeric data directly without using the <code>String</code> initializer that may be faster? Or any other suggestions to speed this up?</p>
  
  <pre><code>func arrayFromContentsOfFileWithPath(path: String) -&gt; [Double]? {
      do {
          let content = try String(contentsOfFile:path, encoding: NSUTF8StringEncoding)
          let stringArray = content.componentsSeparatedByString("\n").map{
              $0.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
          }
          return stringArray.map{Double($0)}.flatMap{$0}
      } catch _ as NSError {
          return nil
      }
  }
  </code></pre>
  
  <p><strong>EDIT:</strong>
  To quantify things a  bit, the data file is 10000 samples and the load time is 0.183 s for a single load (according to a <code>measureBlock</code> in my unit tests). In comparison, MATLAB loads the file in 0.033 s. Here are the first few samples of the data:</p>
  
  <pre><code>   8.1472369e-01
     9.0579194e-01
     1.2698682e-01
     9.1337586e-01
     6.3235925e-01
     9.7540405e-02
     2.7849822e-01
     5.4688152e-01
     9.5750684e-01
     9.6488854e-01
  </code></pre>
  
  <p><strong>UPDATE:</strong> 
  Following @appzYourLife's advice to combine the mappings (I used <code>.flatMap{Double($0)}</code>) and to use a Release build, the load time is now 0.119 s. Much better, but still about 4x the time of MATLAB, which was very unexpected.</p>