SWIFT

Swift String Interpolation: Syntax, Usage, and Examples

String interpolation in Swift lets you embed values, expressions, or even function calls directly into string literals. It’s a simple and powerful way to construct dynamic strings that are clean and readable.


How It Works

You use string interpolation by wrapping an expression inside \() within a string:

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

You can interpolate variables, arithmetic, booleans, or function results:

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

Swift evaluates the expression inside the parentheses and converts the result into a string at runtime.


When to Use It

1. Displaying Values in the UI

It’s ideal for showing live data like names, scores, or dates:

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

2. Logging and Debugging

Interpolation simplifies debug print statements:

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

3. Alerts and Labels

Dynamic text in notifications or labels becomes easier to construct:

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

4. Combining Computed Values

You can interpolate the output of functions or calculations:

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

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

Common Examples

Personalized Greetings

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

Weather Output

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

Conditional Text

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

Currency Formatting with NumberFormatter

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

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

Formatting Options

Using String(format:)

For more control over decimal places or specific formatting:

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

You can combine this with interpolation:

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

Multiline Interpolation

Triple-quoted string literals support interpolation too:

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

This works well for emails, templates, or documentation blocks.


Working with Arrays and Collections

Interpolation handles collection types like arrays or dictionaries:

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

For custom formatting:

let formatted = items.joined(separator: ", ")
print("Items: \(formatted)")

Interpolation with Custom Types

You can control how custom types appear using CustomStringConvertible:

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

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

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

Nesting Functions Inside Interpolation

It’s valid to call functions inside interpolated expressions:

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

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

As long as the result is a printable value, it works seamlessly.


Performance Considerations

Interpolation is efficient in most cases, but watch out in performance-critical loops:

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

For large outputs, use string builders instead of repeated interpolation:

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

Summary

String interpolation in Swift is one of the language’s most useful features for constructing readable, dynamic strings. You can interpolate everything from simple values to function calls, conditionals, and formatted numbers.

Whether you’re debugging, presenting data to users, or building text for your UI, interpolation keeps your code cleaner and easier to maintain than traditional concatenation. Once you’re comfortable with \(expression) syntax, it becomes second nature in your Swift toolkit.

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