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.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 13, 2024 (grammar).