create a file in swift

To create a file in Swift, you can use the FileManager class which provides methods for creating, deleting, moving and copying files and directories.

The following code snippet creates a new file named "example.txt" in the documents directory of your app:

main.swift
let fileName = "example.txt"
guard let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let fileURL = documentsURL.appendingPathComponent(fileName)

do {
    try "Hello, World!".write(to: fileURL, atomically: false, encoding: .utf8)
} catch {
    print("Error writing to file: \(error)")
}
349 chars
10 lines

This creates fileURL by appending the fileName to the URL for the documents directory, then writes the string "Hello, World!" to the file using the .write(to:atomically:encoding:) method.

If the file already exists, this code will overwrite its contents. If you'd like to add to an existing file, you can use the FileHandle class to append data to the end of a file.

gistlibby LogSnag