title: How to create a CSV file using Swift
body: <p>In an app I created to collect data from <code>Apple</code> pencil input, I tried to export the data into a CSV file. But so far, I only managed to create a single column which records the time length. I want to add another column to record the force from the <code>Apple</code> pencil.</p>
  
  <p>This is what I have tried to do:</p>
  
  <pre><code>var patientsData:[Dictionary&lt;String, AnyObject&gt;] = Array()
  var dct = Dictionary&lt;String, AnyObject&gt;()
  
  // MARK: CSV writing
  func createCSVX(from recArray:[Dictionary&lt;String, AnyObject&gt;]) {
  var csvString = "\("Time")\n"
  dct.updateValue(TestDraw.time as AnyObject, forKey: "T")
  csvString = csvString.appending("\(String(describing: dct["T"]))\n")
  patientsData.append(dct)
  let fileManager = FileManager.default
  do {
      let path = try fileManager.url(for: .documentDirectory, in: .allDomainsMask, appropriateFor: nil, create: false)
      let fileURL = path.appendingPathComponent("TrailTime.csv")
      try csvString.write(to: fileURL, atomically: true, encoding: .utf8)
  } catch {
      print("error creating file")
      }
  
  }
  </code></pre>
  
  <p>I know I can write another function to create another <code>CSV</code> file with a single column to record the force, but I would like to record them in a single spreadsheet​.</p>
  
  <p>Also, does anyone know how to remove the "Optional" in the <code>CSV</code> file created?</p>
  
  <p>This is what I have tried based on one of the answers.</p>
  
  <pre><code>func createCSVX(from recArray:[Dictionary&lt;String, AnyObject&gt;]) {
  var csvString = "\("Time"),\("Force")\n"
  
  dct.updateValue(TestDraw.time as AnyObject, forKey: "T")
  
  dct.updateValue(TestDraw.force as AnyObject, forKey: "F")
  
  patientsData.append(dct)
  
  csvString = csvString.appending("\(String(describing: dct["T"])), \(String(describing:   dct["F"]))\n")
  
  let fileManager = FileManager.default
  
  do {
  
  let path = try fileManager.url(for: .documentDirectory, in: .allDomainsMask, appropriateFor: nil , create: false )
  
  let fileURL = path.appendingPathComponent("TrailTime.csv")
  
  try csvString.write(to: fileURL, atomically: true , encoding: .utf8)
  } catch {
  
  print("error creating file")
  
  }
  
  print(TestDraw.force)
  
  }
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/Rdnfx.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Rdnfx.jpg" alt="Screeshot of the exported CSV file"></a></p>