append to a file in swift

To append text to a file in Swift, you can use the FileHandle class provided by the Foundation framework. First, you need to get the file handle for the file to which you want to append the text. You can do this using the FileHandle(forWritingAtPath:) method. If the file does not exist, this method returns nil, and you need to create the file using FileManager before getting the file handle.

Here's an example code snippet that shows how to append text to a file:

main.swift
let text = "Hello, world!"
if let data = text.data(using: .utf8),
   let fileHandle = FileHandle(forWritingAtPath: "/path/to/file") {
    defer {
        fileHandle.closeFile()
    }
    fileHandle.seekToEndOfFile()
    fileHandle.write(data)
}
245 chars
10 lines

In this code, text is the string that you want to append to the file. We first convert it to a Data instance using data(using:) method. Then, we check if we can get a file handle for the file at the specified path. If yes, we use fileHandle.seekToEndOfFile() to set the file pointer to the end of the file, and then write the data to the file using the write(_:) method.

It's important to close the file handle when you're done with it, which is why we use defer statement to make sure it gets closed even if there's an error that causes premature exit from the block.

gistlibby LogSnag