SWIFT

Swift String Interpolation: Syntax, Usage, and Examples

Swift string interpolation lets you insert variable values, constants, expressions, or even function calls directly into string literals. It's one of the easiest and most readable ways to build dynamic strings in Swift.

How to Use Swift String Interpolation

String interpolation in Swift is done by wrapping an expression inside a string using \() syntax. You place the expression inside the parentheses, and Swift replaces it with the actual value at runtime.

let name = "Nia"
let greeting = "Hello, \(name)!"
print(greeting)  // Output: Hello, Nia!

This method can include numbers, booleans, calculated expressions, or even function results.

let age = 30
let intro = "I'm \(age + 1) years old next year."

When to Use String Interpolation Swift

Swift string interpolation is incredibly useful when you need to build dynamic or personalized messages. Here are some of the most common use cases:

1. Displaying Variable Values in UI

Any time your app presents data to users—like user names, scores, prices, or dates—Swift string interpolation is a quick way to format that output.

let score = 88
let message = "Your current score is \(score)."

2. Logging and Debugging

Developers often use string interpolation in Swift to insert live variable values into print statements. This makes logs easier to read and debug.

let isConnected = true
print("Network connected: \(isConnected)")

3. Formatted Output in Alerts or Labels

If you're building strings for labels, alerts, or notifications, interpolation allows clean and readable formatting without string concatenation.

let itemCount = 5
let cartText = "You have \(itemCount) items in your cart."

4. Combining Text and Computed Values

Swift string interpolation is ideal for inserting the results of expressions, such as mathematical calculations or function calls.

func calculateDiscountedPrice(price: Double) -> Double {
    return price * 0.9
}

let price = 200.0
let message = "Discounted price: \(calculateDiscountedPrice(price: price)) EUR"

Examples of Swift String Interpolation

Here are some real-world examples to better understand how to apply string interpolation in Swift projects.

Example 1: Greeting Message

let firstName = "Sara"
let lastName = "Chen"
let greeting = "Hi, \(firstName) \(lastName)! Welcome back."
print(greeting)

This outputs a personalized welcome message, which is common in onboarding and login flows.

Example 2: Temperature Display

let temperature = 22.5
let weatherReport = "Today's temperature is \(temperature)°C."
print(weatherReport)

Dynamic values like temperature, currency, and location benefit from interpolation due to their frequent updates.

Example 3: Conditional Message

let isAdmin = false
let statusMessage = "User status: \(isAdmin ? "Admin" : "Regular user")"
print(statusMessage)

Here, Swift string interpolation handles expressions, including ternary logic.

Example 4: Currency Formatting (with NumberFormatter)

You can combine Swift string interpolation with formatting tools like NumberFormatter to show values properly.

let price = 1499.99
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = Locale(identifier: "en_US")

if let formattedPrice = formatter.string(from: NSNumber(value: price)) {
    let message = "The total is \(formattedPrice)."
    print(message)
}

Learn More About String Interpolation in Swift

Using Format Specifiers with Swift String Interpolation

While Swift doesn't use the same format specifiers as C or Objective-C directly within interpolation, you can still use formatted output with the String(format:) initializer.

let pi = 3.14159
let formatted = String(format: "Value of pi is %.2f", pi)
print(formatted)  // Output: Value of pi is 3.14

To use interpolation and format together:

let temperature = 36.685
let formattedTemp = String(format: "%.1f", temperature)
let display = "Temperature: \(formattedTemp)°C"

This is useful when you want more control over decimal places, currency formatting, or percentage display.

Multiline String Interpolation

Swift supports multiline string literals using triple quotes ("""). You can interpolate values inside them as well.

let author = "Ada Lovelace"
let bio = """
Name: \(author)
Known for: First computer algorithm
"""
print(bio)

This is helpful for longer blocks of text, like documentation, templates, or message previews.

Interpolation with Arrays and Collections

When displaying arrays or dictionaries, Swift interpolation automatically converts them into strings.

let items = ["Eggs", "Milk", "Bread"]
let list = "Shopping list: \(items)"
print(list)  // Output: Shopping list: ["Eggs", "Milk", "Bread"]

To customize formatting:

let formattedList = items.joined(separator: ", ")
print("Items: \(formattedList)")  // Output: Items: Eggs, Milk, Bread

Using Custom Types with Interpolation

If you define your own types, Swift lets you customize how they appear in interpolated strings using the CustomStringConvertible protocol.

struct User: CustomStringConvertible {
    var name: String
    var age: Int

    var description: String {
        return "\(name), age \(age)"
    }
}

let user = User(name: "Leila", age: 29)
let profile = "User profile: \(user)"
print(profile)

This makes it easier to generate readable logs and outputs when dealing with structs or classes.

Nesting Interpolation and Function Calls

Interpolation isn’t limited to simple expressions. You can place entire functions inside the interpolation brackets.

func fullName(first: String, last: String) -> String {
    return "\(first) \(last)"
}

let message = "Welcome, \(fullName(first: "Sanjay", last: "Patel"))!"
print(message)

As long as the result is a valid string or printable type, it works.

Performance Tips for Interpolation

Swift string interpolation is optimized for performance in most cases, but if you’re interpolating inside a tight loop or a performance-critical section, be mindful of object creation. Prefer String(format:) when formatting multiple values at once or use string builders for large text outputs.

for i in 1...3 {
    print("Step \(i)")
}

For complex string building:

var result = ""
for number in 1...5 {
    result += "\(number), "
}
print("Counted: \(result)")

Summary

String interpolation in Swift gives you a powerful, readable, and efficient way to construct strings on the fly. You can interpolate everything from simple variables to the output of complex functions, and you can even apply formatting when needed. Compared to older concatenation methods, Swift string interpolation keeps your code cleaner and easier to maintain.

You’ll find yourself using string interpolation Swift code in almost every app you build—whether it’s for showing a score, formatting a message, or generating a custom string to display to your users. Once you get used to the \(expression) syntax, you’ll hardly ever look back.

Learn to Code in Swift for Free
Start learning now
button icon
To advance beyond this tutorial and learn Swift by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH

Reach your coding goals faster