Here's an example code snippet to write an array of data to a CSV file in Swift:
main.swift538 chars19 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