TextOutputStream
Many Swift programs generate output text—this is often done with print method calls. With TextOutputStream
, we can create a struct
that handles this output text.
By specifying the write function, we can perform transformations upon the strings passed to print()
. We can use a string
to save the print messages to a file or process them elsewhere.
We implement the TextOutputStream
protocol with a struct
called UppercaseStream
. A "write" function is implemented on UppercaseStream
.
string
implements TextOutputStream
—we create an empty string
, and pass it as the "to" argument to print.string
, we can print out the entire string
to standard output.UppercaseStream
struct
we defined. We pass it as the "to" argument, and each message is printed immediately in uppercase.struct UppercaseStream: TextOutputStream { func write(_ string: String) { // Print an uppercase version of the string to the standard output. print(string.uppercased(), terminator: "") } } // Step 1: use print to a string. var result = ""; let size = 10 print("Size: \(size)", to: &result) let color = "blue" print("Color: \(color)", to: &result) // Step 2: print string that we printed to. print("RESULT: [\(result)]") // Step 3: use print to a custom TextOutputStream. var stream = UppercaseStream() print("Size: \(size)", to: &stream) print("Color: \(color)", to: &stream)RESULT: [Size: 10 Color: blue ] SIZE: 10 COLOR: BLUE
With TextOutputStream
, the print method in Swift becomes more powerful. We can use print to save data to files, or verify output in some way.
TextOutputStream
. This helps us ensure a program worked correctly.With TextOutputStream
, a protocol in Swift, we can change the behavior of the print method. Strings implement TextOutputStream
, and can be used in place of a custom TextOutputStream
.