A mistake in Apple doc on String?

Below is from Apple doc on String:

Writing to a File or URL

func write(String)
Appends the given string to this string.

func write(to: inout Target)
Writes the string into the given output stream.

I wonder is it correct? These two APIs are defined in stdlib and, as far as I can tell, they have nothing to do with writing string to file or URL.

The correct APIs are defined in Foundation. Below are two examples of them:

extension StringProtocol {
    /// Writes the contents of the `String` to a file at a given
    /// path using a given encoding.
    public func write<T>(toFile path: T, atomically useAuxiliaryFile: Bool, encoding enc: String.Encoding) throws where T : StringProtocol

    /// Writes the contents of the `String` to the URL specified
    /// by url using the specified encoding.
    public func write(to url: URL, atomically useAuxiliaryFile: Bool, encoding enc: String.Encoding) throws
}

Am I misunderstanding something?

Yes, I think it's wrong. The APIs are related to the TextOutputStream protocol which you could use to write to a file but you don't have to.

I wonder how to do it? I'm aware that macOS is a UNIX system and everything in UNIX is a file and a file is a stream of bytes. But it seems Foundation library doesn't even have a type for file, not to mention conform to the TextOutputStream protocol.

it seems Foundation library doesn't even have a type for file

There are several ways you can output to a file. The traditional way is to use a FileHandle. You can extend that class to conform to TextOutputStream. Of course you have to be careful about how you handle character encodings. There's also FileDescriptor in Swift-System - same provisos with respect to character encodings.

1 Like