Best way to append text to a text file?

Is there an easy way to do this in Swift (which I have missed)?

Assuming there isn't, what would be the best way to implement it?

I started something like this:

extension String {
  func append(to url: URL, atomically: Bool, encoding: Encoding) throws {
    // ...
  }
}

But questions popped up, like:
Should I use FileHandle, OutputStream or something else?
What should a failing self.data(using: encoding) or OutputStream(url:, append:) throw?

Do you need appends to be atomic? That is, as supported by the O_APPEND flag for open.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

I'd like a method that gave me the choice:

just like String's write(to: atomically: encoding:).

OK. Returning to your original questions:

Is there an easy way to do this in Swift (which I have missed)?

No.

Assuming there isn't, what would be the best way to implement it?

Personally, I do this sort of thing with Posix APIs (open, write, and so on). They are ugly, but in a situation like this I prefer to have precise semantics.

What should a failing self.data(using: encoding)

Foundation throws NSFileWriteInapplicableStringEncodingError in this case.

or OutputStream(url:, append:) throw?

Last I checked Foundation doesn’t actually open the file when you create the stream — that work is deferred until you call open — and thus you don’t really need to handle this case [1].

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

[1] AFAICT OutputStream(url:, append:) only returns nil if there’s a memory allocation failure or you pass in something that’s not a file URL. The string write method fails with NSFileWriteUnsupportedSchemeError in the latter case.

2 Likes