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
\( )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 lineString 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 daysAnything 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.
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.
With let habit = "Walk" and let streak = 2, what does print(habit, streak) show?
With streak equal to 6, what does print("Next: \(streak + 1)") show?
What does print("x", "y", "z", separator: "/") show?
With streak equal to 3, what is the value of "\(streak)" + "1"?
Remember
printshows it;\( )puts any value inside a string.- Two passes: evaluate every
\( ), then read the text. printseparates values with a space and ends with a new line unless told otherwise.
