Home / IOS Development / How to define strings, use escape sequences and interpolations?

How to define strings, use escape sequences and interpolations?

As a beginner, it can be difficult to understand string interpolation and escape sequences. In this guide, I will teach you the basics.


What is a string?

According to swift.org and Wikipedia, we can simply say that:

A string is a series of characters


7;s dead simple. This sentence is, for example, a string. When writing computer programs, you usually need to mark the beginning and end of your strings with a special character, these surrounding characters are sometimes called punctuation. Most programming languages ​​use single or double quotes or backticks to specify the boundaries of a string. 💀

Constants, letters, variables and escape

In Swift you can define string literals (constants) by using let keywords or string variables through var keywords. If you do not want to change the value in the future, you can use a string constant, but if you need a more dynamic value, you should use a variable.

let message = "Hello World!"

As you can see, we use double quotes " as delimiters, and we gave the name to ours strict literally (or string constant, which is literally just a non-changing string, hence the name), in this example we can simply call the literal as message.

Now comes the interesting part, how can I put a double quotation mark inside a string literally if it always represents the beginning and / or end of a string? Well, for this reason, the creators introduced many programming languages escapes characters. 😱

let quote = ""One more thing..." - Steve Jobs"

Backslash () character is a very special character when it comes to Swift programming language. We can also use it to write an actual setback by escaping one (\), but the new line (n), tab (t) and returns (r), characters are also created using setbacks. It is also possible to write unicode characters using u{CODE} pattern. This is how it works …

let newline = "n"
    let tab = "t"
    let `return` = "r"
    let unicode = "u{2023}"


Ok, ok, I know, why backticks around the return word? In Swift you can define a constant or variable name with almost any given name that is not a language keyword, you can even use emojis as a name, but if you want to define a variable using a reserved keyword, you must escape it, aka. place it between back pieces. In our case return was an already taken word, so we had to escape it. Let us now return to the more interesting part.

If you take a look at a unicode drawing table, you will see that 2023 belongs to the game symbol. Unicode has so many characters and the list is still growing. Fortunately, Swift can handle them very well, you can print unicode characters straight ahead, or you can use the escape sequence by entering the hexacode of the unicode character.

    let p1 = "𐳠"
    let p2 = "u{10CE0}"

    let s1 = "😊"
    let s2 = "u{1F60A}"

You can play with emojis and look up unicode character codes for them on the Emojipedia website. Since we’ve talked about escaping quite a bit, let me show you a few more things you can do about the setback in Swift.

String interpolation

So we have already seen how we can put special characters in strings, what if I want to put another constant or variable in a string? This is a perfectly valid utility case, and we can actually use the following syntax to place variables in strings in Swift.

let name = "World"
    let message = "Hello (name)!"


Long story short, this escape format ((VARIABLE)) is called string interpolation, and it is a very convenient and powerful tool for all novice Swift programmers. You know that in some other languages ​​you have to use format strings to put variables in other strings, which can be extremely painful in some cases, but in Swift you can simply interpolate almost anything. 🎉

Since we are talking about interpolations, I would like to show you how to connect two strings in Swift.

let welcome = "Hello"
    let name = "World"

    let m1 = welcome + " " + name + "!"
    let m2 = "(welcome) (name)!"


The last two message strings will be identical, the only difference is the way we connected the parts together. In the first scenario, we used + sign to combine the strings, but in the second version we have simply used interpolation to construct a new string using the previously defined constants.

Custom string interpolation

This is a more advanced topic, but I think not many people are aware of this feature in Swift, so let’s talk a little bit about it. The main idea here is that you can create your own custom interpolation methods to format strings. I will show you a working example very quickly.

extension String.StringInterpolation {
    mutating func appendInterpolation(sayHelloTo value: String) {
        appendLiteral("Hello " + value + "!")

let message = "(sayHelloTo: "World")"

This way you can add your string formatter code String.StringInterpolation extension, and you do not have to deal with the rest when you create the variable. The appendInterpolation the function can have several parameters, and you must use them in the interpolation brackets when using it. No worries if this is too much, this topic is quite advanced, just remember that something like this exists and came back later. 💡

I highly recommend reading Paul Hudson’s article on super-driven string interpolation.

Interlining of multi-line string line literals

Back to a relatively simple problem, how about string with multiple lines? Do I have to connect everything line by line to construct something like this? The answer is no. Multi-Line String Literals was introduced in Swift 4, and it was a very nice addition to the language.

let p1 = """
    Please, remain calm, the end has arrived
    We cannot save you, enjoy the ride
    This is the moment you've been waiting for
    Don't call it a warning, this is a war

    It's the parasite eve
    Got a feeling in your stomach 'cause you know that it's coming for ya
    Leave your flowers and grieve
    Don't forget what they told ya, ayy ayy
    When we forget the infection
    Will we remember the lesson?
    If the suspense doesn't kill you
    Something else will, ayy ayy

You can use three double quotes (""") as a delimiter if you want to define long strings. This type of string literature can contain new lines and individual double quotes without having to escape. It is also good to know that if the final delimitation adjustment means something, then if you place a tab or a few spaces before it, you must also adjust everything before to the same column, in this way the hidden spaces / tabs will be ignored. Feel free to try it. 🔨

Newline escape in strict interpolation

There is one problem with very long strings. They’re hard to read because … the strings are freaking long. Consider the following example.

let p1 = """
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Wouldn’t it be cool if we could break this mess into a few small pieces somehow? Yes or of course, you can use strict pairing, but luckily there is a more elegant solution.

// Shorter lines that are easier to read, but represent the same long line, let text2 = “” “Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud training ullamco laboris nisi ut aliquip ex ea commodo consequat. “” ”

The String Newline Escaping Swift evolution proposal was also implemented a long time ago, so we can use the backslash to work with shorter lines and escape the selection from the new line from the end of each line. It is a rather small but nice to have function that can make our lives more enjoyable when we have to work with multi-line ironing literature. No more: n n n. 👍

Raw string escapes

The very last thing I want to show you is based on the Enhancing String Literals Delimiters to Support Raw Text proposal. The motivation behind this was that there are some cases when you have to escape too much in a string, and we should be able to avoid this in some way.

let regex1 = "\\[A-Z]+[A-Za-z]+\.[a-z]+"
    let regex2 = #"\[A-Z]+[A-Za-z]+.[a-z]+"#

In my opinion, the usual expression above is a very good example of this case. By defining a custom delimiter (#" and "#) we can avoid further escaping within our string definition. The only drawback is that now we can not only interpolate substrings, but we must also place a boundary wire there. Let me show you another example here.

let name = "Word"
    let message  = #"Hello "#(name)"!"#


As you can see, it makes quite a difference, but do not worry, you do not need to use this format as much. Honestly, I only used this feature once or twice as far. 😅


Strings in the Swift are easy to learn, but don’t be fooled: they are extremely complicated under the hood. In this article we have learned about unicode characters, coding, escapes, letters and many more. I hope this will help you understand strings a little better.

We’ve also researched a few Swift evolution suggestions, but you can find a complete list of them on the Swift evolution dashboard. These proposals are open source, and they help us make Swift an even better programming language with the help of the community. ❤️

Source link