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?
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.