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:
Learn Swift on Mimo
Swift
let name = "Nia"
let greeting = "Hello, \(name)!"
print(greeting) // Output: Hello, Nia!
You can interpolate variables, arithmetic, booleans, or function results:
Swift
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:
Swift
let score = 88
let message = "Your current score is \(score)."
2. Logging and Debugging
Interpolation simplifies debug print statements:
Swift
let isConnected = true
print("Network connected: \(isConnected)")
3. Alerts and Labels
Dynamic text in notifications or labels becomes easier to construct:
Swift
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:
Swift
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
Swift
let firstName = "Sara"
let lastName = "Chen"
let greeting = "Hi, \(firstName) \(lastName)! Welcome back."
Weather Output
Swift
let temperature = 22.5
let report = "Today's temperature is \(temperature)°C."
Conditional Text
Swift
let isAdmin = false
let status = "User status: \(isAdmin ? "Admin" : "Regular user")"
Currency Formatting with NumberFormatter
Swift
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:
Swift
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:
Swift
let temperature = 36.685
let display = "Temperature: \(String(format: "%.1f", temperature))°C"
Multiline Interpolation
Triple-quoted string literals support interpolation too:
Swift
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:
Swift
let items = ["Eggs", "Milk", "Bread"]
print("Shopping list: \(items)")
For custom formatting:
Swift
let formatted = items.joined(separator: ", ")
print("Items: \(formatted)")
Interpolation with Custom Types
You can control how custom types appear using CustomStringConvertible:
Swift
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:
Swift
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:
Swift
for i in 1...3 {
print("Step \(i)")
}
For large outputs, use string builders instead of repeated interpolation:
Swift
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.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot