Represents the contents of a string literal with interpolations while it’s being built up.
SDK
- Xcode 10.2+
Framework
- Swift Standard Library
Declaration
Overview
Each Expressible
type has an associated String
type which conforms to String
. Swift converts an expression like "The time is \(time)." as My
into a series of statements similar to:
The String
type is responsible for collecting the segments passed to its append
and append
methods and assembling them into a whole, converting as necessary. Once all of the segments are appended, the interpolation is passed to an init(string
initializer on the type being created, which must extract the accumulated data from the String
.
In simple cases, you can use Default
as the interpolation type for types that conform to the Expressible
protocol. To use the default interpolation, conform a type to Expressible
and implement init(string
. Values in interpolations are converted to strings, and then passed to that initializer just like any other string literal.
Handling String Interpolations
With a custom interpolation type, each interpolated segment is translated into a call to a special append
method. The contents of the interpolation’s parentheses are treated as the call’s argument list. That argument list can include multiple arguments and argument labels.
The following examples show how string interpolations are translated into calls to append
:
\(x)
translates toappend
Interpolation(x) \(x, y)
translates toappend
Interpolation(x, y) \(foo: x)
translates toappend
Interpolation(foo: x) \(x, foo: y)
translates toappend
Interpolation(x, foo: y)
The append
methods in your custom type must be mutating instance methods that return Void
. This code shows a custom interpolation type’s declaration of an append
method that provides special validation for user input:
To use this interpolation method, create a string literal with an interpolation using the validating
parameter label.
append
methods support virtually all features of methods: they can have any number of parameters, can specify labels for any or all of their parameters, can provide default values, can have variadic parameters, and can have parameters with generic types. Most importantly, they can be overloaded, so a type that conforms to String
can provide several different append
methods with different behaviors. An append
method can also throw; when a user writes a literal with one of these interpolations, they must mark the string literal with try
or one of its variants.