← Back to Swift Course | Chapter 1: Setup & Basics | Lesson 5 of 7

The print() Function

print() is the command you use to make the computer show text or numbers on the screen so you can see what your program is doing.

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

markup
print("First line")
print("Second line")

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

markup
let name = "Swift"
let version = 5.9
print("Learning \(name) version \(version)")

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

markup
print("apple", "banana", "cherry")
print("apple", "banana", "cherry", separator: " - ")

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

markup
print("Loading", terminator: "")
print("...", terminator: "")
print("done")
Common Mistakes
  1. Forgetting that print automatically adds a newline after each call, leading to unexpectedly stacked output.
  2. Trying to concatenate a number directly to a string with + instead of using string interpolation with \().
  3. Not knowing about the separator and terminator parameters, then manually inserting spaces or newlines that print already handles.
Chapter Summary
  • 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 separator parameter controls what goes between multiple printed items, and terminator controls 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.