Home
Swift
TextOutputStream Example, print
Updated Sep 13, 2024
Dot Net Perls
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.
print
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.
Example. We implement the TextOutputStream protocol with a struct called UppercaseStream. A "write" function is implemented on UppercaseStream.
Step 1 A string implements TextOutputStream—we create an empty string, and pass it as the "to" argument to print.
Step 2 Once we printed some values to the string, we can print out the entire string to standard output.
Step 3 Here we use the 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
More powerful print. 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.
So We can ensure the program printed a certain message with a TextOutputStream. This helps us ensure a program worked correctly.
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 13, 2024 (grammar).
Home
Changes
© 2007-2025 Sam Allen