Interpolation

You can also build up a string by using interpolation, which is a special Swift syntax that lets you build a string in a way that’s easy to read:

let name = "Matt"

let message = "Hello my name is (name)!" // "Hello my name is Matt!"

As I’m sure you’ll agree, this is much more readable than the example from the previous section. It’s an extension of the string literal syntax, whereby you replace certain parts of the string with other values. You enclose the value you want to give the string in parentheses preceded by a backslash.

This syntax works in just the same way to build a string from other data types, such as numbers:

let oneThird = 1.0 / 3.0

let oneThirdLongString = "One third is (oneThird) as a decimal."

Here, you use a Double in the interpolation. At the end of this code, your

oneThirdLongString constant will contain the following:

One third is 0.3333333333333333 as a decimal.

Of course, it would actually take infinite characters to represent one third as a decimal, because it’s a repeating decimal. String interpolation with a Double gives you no way to control the precision of the resulting string.

This is an unfortunate consequence of using string interpolation; it’s simple to use, but offers no ability to customize the output.

results matching ""

    No results matching ""