Menu
Coddy logo textTech

String Interpolation

Part of the Fundamentals section of Coddy's Swift journey — lesson 32 of 86.

String interpolation lets you embed variables and expressions directly inside a string. Instead of joining strings together with the + operator, you place values inside \() within your string.

let name = "Alice"
let age = 25
print("My name is \(name) and I am \(age) years old.")
// Output: My name is Alice and I am 25 years old.

Swift automatically converts the values to strings for you. This works with any type — integers, doubles, booleans, and more.

You can even include expressions that get evaluated on the spot:

let price = 19.99
let quantity = 3
print("Total: $\(price * Double(quantity))")
// Output: Total: $59.97

String interpolation makes your code cleaner and easier to read compared to concatenating multiple strings with +. It's the preferred way to build dynamic strings in Swift.

challenge icon

Challenge

Easy

You are provided with the following variables:

let productName = "Wireless Headphones"
let price = 79.99
let quantity = 2

Use string interpolation to print a receipt line that displays the product information and calculates the total cost.

Print the following message:

Item: Wireless Headphones (x2) - Total: $159.98

Use \() to embed the variables and calculate price * Double(quantity) directly within the string.

Cheat sheet

Use string interpolation to embed variables and expressions inside a string with \():

let name = "Alice"
let age = 25
print("My name is \(name) and I am \(age) years old.")
// Output: My name is Alice and I am 25 years old.

You can include expressions that get evaluated directly:

let price = 19.99
let quantity = 3
print("Total: $\(price * Double(quantity))")
// Output: Total: $59.97

String interpolation works with any type and is cleaner than concatenating with +.

Try it yourself

let productName = "Wireless Headphones"
let price = 79.99
let quantity = 2

// TODO: Use string interpolation to print the receipt line
// Calculate price * Double(quantity) directly within the string
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals