0Pricing
Swift Academy · Lesson

Custom String Interpolation

Extend interpolation with your own segments.

Custom String Interpolation

Swift lets you extend how interpolation works by adding methods to String.StringInterpolation. This customizes what happens for specific argument types or labels.

extension String.StringInterpolation {
    mutating func appendInterpolation(shout value: String) {
        appendLiteral(value.uppercased() + "!")
    }
}
print("Message: \(shout: "hello")")

The appendInterpolation Method

Each custom interpolation is a mutating func appendInterpolation(...). Its parameters define what you write between the parentheses in a string.

extension String.StringInterpolation {
    mutating func appendInterpolation(repeat text: String, times: Int) {
        appendLiteral(String(repeating: text, count: times))
    }
}
print("\(repeat: "ab", times: 3)")

All lessons in this course

  1. Basic String Interpolation
  2. Formatting Numbers in Strings
  3. Multiline String Literals
  4. Custom String Interpolation
← Back to Swift Academy