Bird
Raised Fist0
Swiftprogramming~10 mins

String interpolation in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - String interpolation
Start
↓
Define variables
↓
Create string with \(variable)
↓
Swift replaces \(variable) with value
↓
Final string ready
↓
Print or use string
↓
End
Swift replaces placeholders inside \( ) with variable values to build the final string.
Execution Sample
Swift
let name = "Anna"
let age = 30
let greeting = "Hello, \(name)! You are \(age) years old."
print(greeting)
This code creates a greeting string by inserting variables name and age inside the string.
Execution Table
StepActionExpression EvaluatedResult
1Define variable namename = "Anna"name = "Anna"
2Define variable ageage = 30age = 30
3Create greeting string with interpolation"Hello, \(name)! You are \(age) years old.""Hello, Anna! You are 30 years old."
4Print greetingprint(greeting)Output: Hello, Anna! You are 30 years old.
💡 All variables replaced and string printed, program ends.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
nameundefined"Anna""Anna""Anna""Anna"
ageundefinedundefined303030
greetingundefinedundefinedundefined"Hello, Anna! You are 30 years old.""Hello, Anna! You are 30 years old."
Key Moments - 2 Insights
Why does the string show the variable values instead of the variable names?
Because Swift replaces the \(variable) placeholders with the actual values during string creation, as shown in step 3 of the execution_table.
Can I put expressions inside \( ) or only variables?
You can put any valid Swift expression inside \( ), not just variables. Swift evaluates it and inserts the result, as the concept_flow shows the evaluation step.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of greeting after step 3?
A"Hello, name! You are age years old."
B"Hello, Anna! You are 30 years old."
C"Hello, \(name)! You are \(age) years old."
D"Hello, Anna! You are age years old."
💡 Hint
Check the 'Result' column in row for step 3 in execution_table.
At which step does Swift replace the variables with their values inside the string?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look at the 'Action' and 'Result' columns in execution_table step 3.
If we change age to 31 before creating greeting, what will greeting contain?
A"Hello, Anna! You are age years old."
B"Hello, Anna! You are 30 years old."
C"Hello, Anna! You are 31 years old."
D"Hello, \(name)! You are \(age) years old."
💡 Hint
Refer to variable_tracker and how greeting uses current age value at creation.
Concept Snapshot
Swift String Interpolation:
Use \(variable) inside strings to insert variable values.
Supports any expression inside \( ).
Swift evaluates and replaces placeholders when string is created.
Example: "Hello, \(name)!" becomes "Hello, Anna!" if name = "Anna".
Full Transcript
This visual trace shows how Swift string interpolation works step-by-step. First, variables name and age are defined. Then a string greeting is created using \(name) and \(age) placeholders. Swift replaces these placeholders with the actual values "Anna" and 30 during string creation. Finally, printing greeting outputs the full message with values inserted. The variable tracker shows how each variable changes from undefined to their assigned values. Key moments clarify why placeholders become values and that expressions can be used inside \( ). The quiz tests understanding of when and how interpolation happens and what the final string contains.

Practice

(1/5)
1. What does string interpolation in Swift allow you to do?
easy
A. Convert a string to uppercase or lowercase
B. Create a new string by repeating characters multiple times
C. Split a string into an array of characters
D. Insert variables or expressions directly inside a string using \( )

Solution

  1. Step 1: Understand string interpolation purpose

    String interpolation lets you put variables or expressions inside a string easily.
  2. Step 2: Recognize the syntax

    Using \( ) inside double quotes inserts the value dynamically.
  3. Final Answer:

    Insert variables or expressions directly inside a string using \( ) -> Option D
  4. Quick Check:

    String interpolation = Insert variables with \( ) [OK]
Hint: Remember: \( ) inside quotes inserts values fast [OK]
Common Mistakes:
  • Confusing interpolation with string repetition
  • Trying to use single quotes instead of double quotes
  • Forgetting the backslash before parentheses
2. Which of the following is the correct way to use string interpolation in Swift to show the value of variable score inside a string?
easy
A. "Your score is: ${score}"
B. "Your score is: score"
C. "Your score is: \(score)"
D. "Your score is: {score}"

Solution

  1. Step 1: Identify correct interpolation syntax

    Swift uses \(variable) inside double quotes for interpolation.
  2. Step 2: Check each option

    "Your score is: \(score)" uses \(score), which is correct. Others use wrong syntax.
  3. Final Answer:

    "Your score is: \(score)" -> Option C
  4. Quick Check:

    Swift interpolation = \(variable) [OK]
Hint: Use backslash and parentheses for variables inside strings [OK]
Common Mistakes:
  • Using ${} like in other languages
  • Forgetting the backslash before parentheses
  • Not using double quotes around the string
3. What will be the output of the following Swift code?
let name = "Anna"
let age = 30
print("\(name) is \(age) years old.")
medium
A. Anna is 30 years old.
B. name is age years old.
C. \(name) is \(age) years old.
D. Anna is \(age) years old.

Solution

  1. Step 1: Understand variable values

    name = "Anna", age = 30.
  2. Step 2: Apply string interpolation

    "\(name)" becomes "Anna", "\(age)" becomes "30" in the string.
  3. Final Answer:

    Anna is 30 years old. -> Option A
  4. Quick Check:

    Interpolation replaces variables with values [OK]
Hint: Replace \(variable) with its value inside the string [OK]
Common Mistakes:
  • Printing the literal \(name) instead of value
  • Confusing variable names with strings
  • Missing backslash causing no interpolation
4. Identify the error in this Swift code snippet using string interpolation:
let temperature = 22
print("The temperature is (temperature) degrees.")
medium
A. Missing backslash before parentheses in interpolation
B. Variable temperature is not declared
C. Using single quotes instead of double quotes
D. Parentheses should be square brackets

Solution

  1. Step 1: Check interpolation syntax

    Interpolation requires a backslash before parentheses: \(variable).
  2. Step 2: Identify missing backslash

    Code uses (temperature) without backslash, so it won't interpolate.
  3. Final Answer:

    Missing backslash before parentheses in interpolation -> Option A
  4. Quick Check:

    Backslash is required for interpolation [OK]
Hint: Always add \ before (variable) in strings [OK]
Common Mistakes:
  • Forgetting the backslash
  • Using wrong quote types
  • Assuming parentheses alone interpolate
5. You want to create a message that shows the total price including tax. Given price = 50 and taxRate = 0.1, which Swift code correctly uses string interpolation to print "Total price: 55.0"?
hard
A. print("Total price: \(price + taxRate)")
B. print("Total price: \(price * (1 + taxRate))")
C. print("Total price: \(price * taxRate)")
D. print("Total price: \(price + taxRate * 100)")

Solution

  1. Step 1: Calculate total price with tax

    Total price = price * (1 + taxRate) = 50 * 1.1 = 55.0.
  2. Step 2: Check each option's expression

    print("Total price: \(price * (1 + taxRate))"): print("Total price: \(price * (1 + taxRate))") = 55.0 correct. A: \(price + taxRate) = 50.1 wrong. C: \(price * taxRate) = 5.0 (tax only) wrong. D: \(price + taxRate * 100) = 60 wrong.
  3. Final Answer:

    print("Total price: \(price * (1 + taxRate))") -> Option B
  4. Quick Check:

    Use price * (1 + taxRate) for total [OK]
Hint: Multiply price by (1 + taxRate) inside \( ) [OK]
Common Mistakes:
  • Adding taxRate directly instead of multiplying
  • Forgetting parentheses around (1 + taxRate)
  • Multiplying taxRate by 100 incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard