Swift 5: Understanding of String Interpolation

Payal Maniyar
2 min readApr 17, 2019

Let’s deep dive into “StringInterpolation” which is a cool feature of Swift 5.

With the help of “StringInterpolation”, we can define how the Objects appear in a string at the time of print the Object(while using print function and po while debugging).

While we print Struct, it prints the struct name followed by all its properties. Let’s see via code snippet.

But if we are working with classes and want to print the object, the behaviour is not the same as it is with Struct. Let’s see with the code snippet.

To print the objects of classes as well as the Struct, CustomStringConvertible comes into the picture. Let’s see its use with the code snippet.

If we use CustomStringConvertible, then we can print Object with implementing description property.

String Interpolation can also print the Object with various argument and various result. Let’s understand with code snippet:

In the above code snippet, the argument will decide which StringInterpolation extension to be used.

Let’s move on to more advanced usages…

Your custom interpolation method can take as many parameters as you need, labelled or unlabeled. For example, we could add an interpolation to print numbers using various styles, like this:

You can call `appendLiteral()` as many times as you need, or even not at all if necessary. For example, we could add a string interpolation to repeat a string multiple times, like this:

And, as these are just regular methods, you can use Swift’s full range of functionality. For example, we might add an interpolation that joins an array of strings together, but if that array is empty execute a closure that returns a string instead:

That’s it….

Hope now the use of StringInterpolation is clear now.

--

--