Defining custom string interpolation behavior in Swift

Swift’s string interpolation system is more powerful than it first appears. Beyond simple value substitution, it can be customized to perform additional logic directly inside string literals.

Custom interpolation can be implemented by extending String.StringInterpolation. This allows us to define custom interpolation behavior tailored to specific types or formatting requirements.

The example below adds support for inline formatting using the FormatStyle protocol.

import Foundation

extension String.StringInterpolation {
    mutating func appendInterpolation<F: FormatStyle>(
        _ value: F.FormatInput,
        format: F
    ) where F.FormatInput: Equatable, F.FormatOutput == String {
        appendLiteral(format.format(value))
    }
}

With this extension in place, a Date can be formatted directly within a string literal.

let today = Date()

let formattedString = """
Today's date is \(today, format: .dateTime.year().month().day())
"""

// Today's date is 13 Jan 2026
print(formattedString)

Here, the interpolation extension applies the provided format style and inserts the formatted result into the string. This makes the formatting more expressive, avoids repetition, and keeps the interpolation logic close to where it's used.

Custom string interpolation is not limited to formatting. It can be used to validate values, apply conditional logic, or control how domain specific values are rendered. This lets us encode that behavior once and reuse it across string literals.

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Level up your Swift skills!$35

100+ tips to take your Swift code to the next level

Swift Gemsby Natalia Panferova

  • Advanced Swift techniques for experienced developers bypassing basic tutorials
  • Curated, actionable tips ready for immediate integration into any Swift project
  • Strategies to improve code quality, structure, and performance across all platforms

Level up your Swift skills!

100+ tips to take your Swift code to the next level

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Swift Gems

by Natalia Panferova

$35