Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Swift Basics  ›  Lesson

Print and String Interpolation

Print & String Interpolation 12 minprint writes values to the console separated by spaces, and string interpolation with a backslash and brackets places any value or expression inside a string.

Print and String Interpolation

While building Sprout you constantly want to see what a value is right now: is the streak 4 or 5? print shows it in the console, and string interpolation lets you drop values straight into text, both for debugging and for the words users read on screen.

The rule

print shows it; \( ) puts any value inside a string.

print writes to the console and adds a new line at the end. Give it several values and it puts a space between them:

let habit = "Read"
var streak = 4
print(habit, streak)                   // Read 4
print("a", "b", separator: "-")        // a-b
print("Loading", terminator: "...")    // Loading... and no new line

String interpolation puts a value inside a string literal. Write a backslash, then the value in brackets:

print("\(habit): \(streak) days")          // Read: 4 days
print("Tomorrow: \(streak + 1) days")      // Tomorrow: 5 days

Anything inside \( ) is worked out first, then turned into text. You can put an expression there, not only a name. This is exactly what the SwiftUI line Text("You have \(habitCount) habits today") was doing in the first lesson.

For text that runs over several lines, use three quote marks:

let summary = """
    Habit: \(habit)
    Streak: \(streak)
    """

The shortcut

Read a string with interpolation in two passes. First, work out every \( ) to a value. Then read the string as plain text with those values pasted in.

Predicting Sprout's status lineStep 1 of 3
  1. The line

    print("\(habit) streak: \(streak * 2) of \(streak + 4)") with habit "Read" and streak 3.

A trap to watch: "\(streak)" + "1" is two strings joined, so it gives "31" for a streak of 3, not 4. Do the maths inside the brackets instead: "\(streak + 1)".

Drills

Answer fast — trust the rule.

quick drill

With let habit = "Walk" and let streak = 2, what does print(habit, streak) show?

quick drill

With streak equal to 6, what does print("Next: \(streak + 1)") show?

quick drill

What does print("x", "y", "z", separator: "/") show?

quick drill

With streak equal to 3, what is the value of "\(streak)" + "1"?

Remember

  • print shows it; \( ) puts any value inside a string.
  • Two passes: evaluate every \( ), then read the text.
  • print separates values with a space and ends with a new line unless told otherwise.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainBuild a status line

Sprout has let habit = "Stretch", let done = 3 and let goal = 5. Write one line that prints 'Stretch: 3 of 5 done, 2 to go' using string interpolation, and explain how Swift builds it.