write to a file in swift

To write to a file in Swift, you can use the FileManager class to access the file system and then use the write method of the Data class to write your data to the file.

Here's an example:

main.swift
// Get a reference to the document directory
guard let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
    return
}

// Choose a name for your file
let fileURL = dir.appendingPathComponent("myFile.txt")

// Convert your data to a Data object
let myData = "Hello, world!".data(using: .utf8)

// Write the data to the file
do {
    try myData?.write(to: fileURL)
} catch {
    print("Error writing to file: \(error)")
}
460 chars
18 lines

In this example, we first get a reference to the document directory using the urls(for:in:) method of the FileManager class. We then choose a name for our file and create a URL to it using the appendingPathComponent(_:) method.

Next, we convert our data (a string in this case) to a Data object using the data(using:) method. Finally, we use the write(to:) method to write the data to the file. Any errors that occur during the write operation are caught in the catch block.

gistlibby LogSnag