In Swift 5.8, we can develop console programs that output data to a terminal. The print()
method automatically inserts a newline, but this can be changed.
For debugging, many developers prefer print statements—these help us track control flow in programs. No complicated interfaces are required.
This Swift program uses many calls to print strings and other values to the console. In Xcode these will appear in an output section of the window.
print()
, such as Strings and Ints. For clear code, it is best not to convert to a string
.Print()
adds a newline after the argument. We can specify a separator and terminator.string
interpolation syntax to write more complex data. We use an escaped parenthesis syntax.// Call print with strings. // ... No newline is inserted. print("one ") print("two ") // An Int can be printed. print(3) // Print can handle multiple arguments. // ... Specify a separator and a terminator. print("cat", "dog", "bird", separator: ";", terminator: ".\n") // Print a bool. print(true)one two 3 cat;dog;bird. true
Sometimes we want to call print()
and have no trailing newline. We must specify the "terminator" as an empty string
. This avoids a trailing newline.
var letters: [Character] = ["a", "b", "c", "d"] // Loop over characters in array. for c in letters { // Print with no terminator. print(c, terminator: "") }abcd
String
interpolationOften we need to print multiple variables in a single line, with some text in between them (like labels). String
interpolation is ideal here.
string
interpolation. Here we separate two values with a ":" character.var number = 10 var title = "The Sound and the Fury" // Print with format string. // ... String interpolation inserts both variables. print("\(number): \(title)")10: The Sound and the Fury
CustomStringConvertible
The print function will access a description property on types that implement CustomStringConvertible
. This way we can improve print output of classes.
class
inherits from CustomStringConvertible
and we provide a description. Print uses the description to write to the screen.class Box: CustomStringConvertible { var description: String { // Return a string that represents this instance. return "Box string representation" } } // Create new instance of class. let b = Box() // Print with CustomStringConvertible. print(b)Box string representation
With print, a versatile method, we write to the console. Swift works well for console programs, but apps are a primary target as well.