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
- Basic String Interpolation
- Formatting Numbers in Strings
- Multiline String Literals
- Custom String Interpolation