create a csv file in swift

To create a CSV file in Swift, you need to perform the following steps:

  1. Create a string that contains comma-separated values.
  2. Create a file path URL where you want to save the CSV file.
  3. Open a file handle using the FileHandle class.
  4. Write the data to the file using the write method of the file handle.
  5. Close the file handle using the closeFile method.

Here's an example code snippet that creates a CSV file with headers "Name" and "Age" and two rows of data:

main.swift
let headers = "Name,Age\n"
let row1 = "John,30\n"
let row2 = "Jane,25\n"
let csvString = headers + row1 + row2

if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
    let fileURL = dir.appendingPathComponent("data.csv")
    do {
        try csvString.write(to: fileURL, atomically: true, encoding: .utf8)
        print("CSV file created successfully!")
    } catch {
        print("Error creating CSV file: \(error)")
    }
}
467 chars
15 lines

In this code, we first create a string csvString that contains the header and two rows of data. We then get the URL for the document directory and append the file name "data.csv" to it. We then use try and catch to handle any errors that may occur while writing the data to the file. Finally, we print a success message or an error message to the console depending on the result.

This code uses the write method of the String class to write the data to the file in the specified encoding (UTF-8 in this case). You can also use the FileHandle class to write data to a file in binary format, which may be more efficient for large data sets.

gistlibby LogSnag