W1040 Printing and String Interpolation
A teletype machine (or teleprinter) is an electromechanical device which can be used to send and received typed messages over a distance. It was one of the first devices which enabled the layman, not trained in Morse Code, to communicate easily with another.
In addition to processing commands to print printable characters the teletype processed non-printable characters. The most common of these are:
- A control character (ASCII code 0x09) used to move a device's position to the next horizontal tab stop.
- LINE FEED
- A control character (ASCII code 0x0A) used to move a device's position to the next line. Abbreviated as LF.
- CARRIAGE RETURN
- A control character (ASCII code 0x0D) used to reset a device's position to the beginning of a line of text. Abbreviated as CR.
The print function is one of the most basic functions available and is also one of the most useful. It provides us with the ability to easily output data from our program, most often to the console. As such, it is invaluable for both a completed programming and for assisting us to debug a program during development.
In its most basic form, the print function takes a single argument. It's able to print integers, floating points, Booleans, and strings.
The print function can also print multiple items of various types.
By default, each of the items is separated by a space character. Swift enables us to easily change this separator to any character (or characters) that we'd prefer:
Mutliple Items on a Single Line
By default, Swift will insert a new line at the end of each print statement. Consider:
Swift enables us to easily change this terminator to any character (or characters) that we'd prefer:
We can use special characters to alter what we're printing:
- \t represents a Tab
- \n represents a Newline
- \r represents a Carriage return
Consider the newline:
Consider the carriage return:
Consider the tab:
Strings can be combined by using the + concatenation operator:
let s1 = "The" let s2 = " Inner " let s3 = "Light" print(s1 + s2 + s3) // Prints: // The Inner Light
String interpolation enables us to easily form complex strings by interpolating other values (literals, constants, variables, and expressions) into the string. The values to be interpolated are enclosed within parentheses and preceded by a backslash. For example:
let a = 7 * 7 let b = 4.0 * 4.0 let c = false print("This is a string. 7 * 7 is \(a). 4.0 * 4.0 is \(b). The opposite of true is \(c).") // Prints: // This is a string. 7 * 7 is 49. 4.0 * 4.0 is 16.0. The opposite of true is false.
By default, a user's console output (nowadays to a screen) is fed from a program through the standard output stream. This stream of data is established by the operating system and connected to the running program automatically.