The print() Function
In this page:
print(value)
print("text \(expression)") // interpolation
print(value1, value2, separator: " ")
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 +.
- You can put any expression inside the parentheses, not just a variable, e.g.
\(2 + 2).
Example: String Interpolation
// Declare a constant `name`, set to `"Swift"`
let name = "Swift"
// Declare a constant `version`, set to `5.9`
let version = 5.9
// Print "Learning \(name) version \(version)" to the console
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.
terminator: "" is handy for building up a single line of output across multiple print calls.Example: Custom terminator
// Print "Loading", terminator: "" to the console
print("Loading", terminator: "")
// Print "...", terminator: "" to the console
print("...", terminator: "")
// Print "done" to the console
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: