Skip to content

👩🏻‍💻 🧑🏽‍💻 Subscribe and Read us on Substack to Get Full Access to Our Posts


String Interpolation in Swift

String Interpolation in Swift is a method for constructing new String values by embedding expressions within a string literal. It’s a handy way to integrate constants, variables, and expressions directly within a string, providing versatility in string formatting and data display.

Basics of String Interpolation

Simple Example

let name = "Alice"
let greeting = "Hello, \(name)!"
print(greeting)  // Outputs "Hello, Alice!"

Advanced Usage

Advanced Example: Custom Types

struct User {
    let name: String
    let age: Int
}

let user = User(name: "Bob", age: 30)
let userDescription = "User Details: \(user.name), \(user.age) years old"
print(userDescription)  // Outputs "User Details: Bob, 30 years old"

This example shows how to embed a custom type’s properties within a string using String Interpolation.

Using String Interpolation for Localization

String Interpolation can be used effectively for localization, allowing you to create strings that adapt based on user settings.

Localization Example

First, you need to define the localized strings in .strings files for each language your app supports.

For instance, you might support English and French. Create two .strings files:

  • Localizable.strings (English)
  • Localizable.strings (French)

In each file, define a localized string with placeholders for the user’s name and the date:

English (en.lproj/Localizable.strings)

"greeting" = "Hello, %@! Today is %@.";

French (fr.lproj/Localizable.strings)

"greeting" = "Bonjour, %@! Nous sommes le %@.";

Swift Code for Localization and Interpolation

In your Swift code, you would use NSLocalizedString to fetch the correct localized string, and then use String(format:) for interpolation.

Here’s an example Swift code snippet:

import Foundation

// Example user name and date
let userName = "Alice"
let currentDate = DateFormatter.localizedString(from: Date(), dateStyle: .long, timeStyle: .none)

// Fetch the localized string
let localizedGreetingTemplate = NSLocalizedString("greeting", comment: "Greeting with user name and date")

// Interpolate the user name and date into the localized string
let greeting = String(format: localizedGreetingTemplate, userName, currentDate)

print(greeting)
  • Date Formatting: DateFormatter.localizedString is used to get a localized representation of the current date. The date style is set to .long to include the full date.
  • Localization and Interpolation: NSLocalizedString fetches the correct format string based on the user’s current language setting. String(format:) then replaces the %@ placeholders in the localized string with userName and currentDate.

With this setup, if the user’s device is set to English, they might see:

Hello, Alice! Today is January 16, 2024.

If set to French, they might see:

Bonjour, Alice! Nous sommes le 16 janvier 2024.

Customizing String Interpolation

Swift allows you to customize the interpolation process for advanced formatting.

Custom Interpolation Example

extension String.StringInterpolation {
    mutating func appendInterpolation(_ value: Int, asCurrency currency: String) {
        let formatted = "\(currency) \(value)"
        appendLiteral(formatted)
    }
}

let price = 50
let message = "The price is \(price, asCurrency: "$")"
print(message)  // Outputs "The price is $50"

This extension adds a custom interpolation method to format an integer as a currency.

Conclusion

Understanding and using String Interpolation in Swift is key to writing efficient and readable code. It simplifies the creation of dynamic strings, from basic use cases to complex scenarios like localization and custom formatting.

Back To Top
Search