Swift Output
The print() function is how a Swift program talks to you in the console. It is simple at first sight, but it has a few useful options.
Printing text and values
print accepts any value — text, numbers, booleans, arrays — and writes it followed by a line break.
print("Welcome to Swift")
print(42)
print(3.75)
print(true)
print([1, 2, 3])Welcome to Swift
42
3.75
true
[1, 2, 3]
Several values at once
Pass multiple values separated by commas. By default they are joined with a single space:
let item = "Coffee"
let price = 3.5
print("Item:", item, "Price:", price)
print(1, 2, 3, separator: " - ")
print("a", "b", "c", separator: "")Item: Coffee Price: 3.5
1 - 2 - 3
abc
Staying on the same line
The terminator parameter replaces the line break that print adds at the end. Use an empty string to keep printing on the same line:
for i in 1...5 {
print(i, terminator: " ")
}
print() // an empty print() just ends the line
print("Loading", terminator: "")
print("...", terminator: "")
print(" done!")1 2 3 4 5
Loading... done!
| Parameter | Default | What it does |
|---|---|---|
separator |
" " |
Text placed between the values |
terminator |
"\n" |
Text written after the last value |
Mixing text and values
The cleanest way to build a message is string interpolation: write \(expression) inside a string literal.
let player = "Mia"
let score = 1250
let level = 7
print("\(player) reached level \(level) with \(score) points.")
print("Next level in \(10 - level) levels")Mia reached level 7 with 1250 points.
Next level in 3 levels
Tip: You can also join strings with
+, but every piece must already be aString. Interpolation converts numbers and other values automatically, so it is usually easier.
Multi-line text
Three double quotes start a multi-line string literal. Every line break inside it is kept:
let receipt = """
==== RECEIPT ====
Tea x2
Cake x1
=================
"""
print(receipt)==== RECEIPT ====
Tea x2
Cake x1
=================
The indentation before the closing """ is removed from every line, so you can indent the literal together with your code.
debugPrint and dump
For debugging, two variants show more detail:
let words = ["one", "two"]
print(words)
debugPrint("quoted text")
dump(words)["one", "two"]
"quoted text"
▿ 2 elements
- "one"
- "two"
Test yourself
What does print("a", "b", separator: "+") output?
- a b
- a+b
- ab+
- "a"+"b"
How do you print without moving to a new line?
- print(x, newline: false)
- print(x, terminator: "")
- printInline(x)
- print(x);
Which syntax inserts the value of score into a string?
- "Score: ${score}"
- "Score: {score}"
- "Score: \(score)"
- "Score: %score"