write to a csv file in swift

Here's an example code snippet to write an array of data to a CSV file in Swift:

main.swift
let data: [[String]] = [["Name", "Age", "Country"], ["John", "30", "USA"], ["Lucy", "25", "Canada"], ["David", "40", "UK"]]

let fileName = "output.csv"
let path = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)
var csvText = ""

for row in data {
    let rowText = row.joined(separator: ",")
    csvText.append(rowText)
    csvText.append("\n")
}

do {
    try csvText.write(to: path!, atomically: true, encoding: String.Encoding.utf8)
} catch {
    print("Failed to create file")
    print("\(error)")
}
538 chars
19 lines

In this example, we first define an array data that contains the data we want to write to the CSV file. Then we define a fileName for the output file and create a temporary file path for it.

Next, we loop through each row of our data array and join its elements with commas to create a CSV-formatted row. We add each row to the csvText string with a newline character to separate rows.

Finally, we use the write(to:atomically:encoding:) method to write our csvText to the file path we created earlier. We specify String.Encoding.utf8 as the encoding type for our file.

If the write operation is successful, the output file will be created at the temporary file path. Note that if a file already exists at that location, it will be overwritten with the new data.

gistlibby LogSnag