What printing does
A program does most of its work out of sight. To see a result, you ask the program to show it. In Swift the simplest way is the print() function, which writes a value to the console, the text panel where a running program shows its output and where the compiler reports errors. Whatever a program writes there is its output.
This program prints a number:
print(13)
The console shows:
13
You put the value between the parentheses. Swift evaluates it and prints its text form. Numbers, strings, booleans and arrays all work:
print(42)
print(3.5)
print(true)
print([1, 2, 3])
42
3.5
true
[1, 2, 3]
Each call ends the line
After the value, print() adds an invisible newline character, the same thing that pressing Enter inserts in a text editor. The next piece of output therefore starts on a fresh line, and the cursor does not sit on the line you just wrote. There is no blank line after 13; the newline only ends the line that holds it.
Because of this, several calls produce several lines:
print(1)
print(2)
print(3)
1
2
3
Calling print() with nothing in the parentheses prints only the newline, which gives you an empty line.
Printing several values and changing the ending
You can pass several values, separated by commas. By default print puts a single space between them:
print(1, 2, 3)
print(1, 2, 3, separator: "-")
1 2 3
1-2-3
The newline at the end can be replaced too, with the terminator argument. An empty terminator keeps the next output on the same line:
print("a", terminator: "")
print("b")
ab
Numbers and text are different
A number is written without quotes. Text, called a string, goes in double quotes. The two can print identically, but they are different things to Swift:
print(12 + 3)
print("12" + "3")
15
123
The first line does arithmetic on numbers. The second joins two strings. Strings get their own lesson; for now, remember that quotes turn a value into text.
Common mistakes
- Spelling. The function is
print, all lowercase.Print(13)andprnt(13)make the compiler report that it cannot find the name in scope. - Missing parentheses.
print 13is not a call. Swift needs the parentheses. - Unwanted quotes.
print("1998")andprint(1998)look the same in the console, but only the second one is a number. - Expecting a space after a terminator of "". Nothing is added between the outputs, so include any space you want in the text.
The exercise
The task is to print the number 1998. Write print, open a parenthesis, type the number without quotes, and close the parenthesis:
print(1998)
Running it shows 1998 on its own line.
Key takeaways
print()writes a value to the console.- It ends each call with a newline, so separate calls give separate lines.
- Several values in one call are separated by a space unless you set
separator. - Use
terminator: ""to stay on the same line. - Numbers have no quotes. Text is written inside double quotes.
