TExcelTAD
Home › Swift › Swift Output

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.

swift · try it yourself
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:

swift · try it yourself
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:

swift · try it yourself
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.

swift · try it yourself
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 a String. 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:

swift · try it yourself
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:

swift · try it yourself
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?

  1. a b
  2. a+b
  3. ab+
  4. "a"+"b"

How do you print without moving to a new line?

  1. print(x, newline: false)
  2. print(x, terminator: "")
  3. printInline(x)
  4. print(x);

Which syntax inserts the value of score into a string?

  1. "Score: ${score}"
  2. "Score: {score}"
  3. "Score: \(score)"
  4. "Score: %score"