The print() Function
In this page:
Basic Printing
The simplest use of print takes a single string and writes it to the console, automatically adding a newline character at the end so the next print call starts on a fresh line.
Example: Basic Printing
print("First line")
print("Second line")
Login to try C/C++/Java/PHP code in the editor
String Interpolation
Swift lets you embed variables and expressions directly inside a string using \(expression), which is far cleaner than concatenating strings with +.
Note: You can put any expression inside the parentheses, not just a variable, e.g. \(2 + 2).
Example: String Interpolation
let name = "Swift"
let version = 5.9
print("Learning \(name) version \(version)")
Login to try C/C++/Java/PHP code in the editor
Multiple Arguments and separator
print accepts multiple comma-separated values and joins them with a space by default. The separator parameter customizes what appears between them.
Example: Multiple Arguments and separator
print("apple", "banana", "cherry")
print("apple", "banana", "cherry", separator: " - ")
Login to try C/C++/Java/PHP code in the editor
Custom terminator
By default print ends with a newline, but the terminator parameter can replace that with something else, such as an empty string to keep printing on the same line.
Note: Using terminator: "" is handy for building up a single line of output across multiple print calls.
Example: Custom terminator
print("Loading", terminator: "")
print("...", terminator: "")
print("done")
Login to try C/C++/Java/PHP code in the editor
- Forgetting that
printautomatically adds a newline after each call, leading to unexpectedly stacked output. - Trying to concatenate a number directly to a string with
+instead of using string interpolation with\(). - Not knowing about the
separatorandterminatorparameters, then manually inserting spaces or newlines thatprintalready handles.
print()writes text to standard output, followed by a newline by default.- String interpolation with
\(value)embeds variables and expressions directly inside a string. - The
separatorparameter controls what goes between multiple printed items, andterminatorcontrols what comes after. - print() can take multiple comma-separated arguments, printed with a space between them by default.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: