Swift Output

Learn how to display information to the console using print and string interpolation.

The print() Function

The most common way to produce output in Swift is the `print()` function. It writes text to the console, followed by a newline by default, making it the go-to tool for debugging and displaying results while learning.

Basic print()

print("Hello, Swift learners!")
print(42)
print(3.14)

Printing Multiple Values

You can pass multiple values to `print()` separated by commas, and Swift will join them with a space by default. You can also customize the separator and what's printed at the end using the `separator` and `terminator` parameters.

Custom Separator and Terminator

print("Swift", "is", "fun", separator: "-")
print("No newline here", terminator: " ")
print("...continued on the same line")

String Interpolation

String interpolation lets you embed variables and expressions directly inside a string using `\(expression)`. This is the preferred way to build strings dynamically in Swift, replacing manual concatenation with the `+` operator.

String Interpolation Examples

let firstName = "Ravi"
let score = 95

print("\(firstName) scored \(score) points!")
print("Double the score is \(score * 2)")
print("Rounded average: \(Double(score) / 2.0)")
  • Use `\(variable)` to insert a variable's value into a string
  • Interpolation supports full expressions, not just variable names, e.g. `\(a + b)`
  • String concatenation with `+` still works but is less flexible than interpolation
  • `print()` automatically converts numbers, booleans, and other types to text
ApproachExampleResult
Concatenation"Score: " + String(score)Score: 95
Interpolation"Score: \(score)"Score: 95
Multiple values in printprint("Score:", score)Score: 95
Note: String interpolation is generally preferred over concatenation because it avoids manual type conversions and reads more naturally.
Note: Behind the scenes, `print()` calls each value's textual representation, which is why you can pass numbers, booleans, and strings directly without converting them yourself.

Exercise: Swift Output

Which built-in function writes text to the console in Swift?