Start learning free

LESSON 55 OF 415 · STRINGS I

Escaping Characters in Swift: Quotes, Backslashes and \n

Lesson Read the full explanation

There are times when we want to use quotes inside a string. For example, suppose we want to print the message I am John "the coder" Doe:

print("I am John "the coder" Doe")

You can already see by the text color that we have a problem. Swift recognizes the string to be only I am John .

Swift finds the first quotation mark and interprets that the string starts there. But then, it finds the second quotation mark (after John ) and interprets the string ends there.

Character escaping comes to our rescue!


Escaping characters:

In Swift, some characters serve different functions and so cannot be displayed or printed like other characters. These characters are referred to as special characters.

For example, double quotes (") is considered a special character by Swift. Its job is to let Swift know when a string declaration starts / ends.

There is a way to print special characters like these in Swift, and that is by using the backslash character (\).

When we put \ before a special character, we tell Swift:

"Hey, I know this is a special character, but I don't want to use it like that here. I just want to print it like I print any other character."

For example, when putting a \ before a double quote, Swift no longer interprets that as being the end of the string:

print("I am John \"the coder\" Doe")

print("After \"Coding 101\" we'll solve some problems")

The output of this code is:

I am John "the coder" Doe
After "Coding 101" we'll solve some problems

Escaping backslash:

Sometimes we might want to print strings that contain character \, such as a file path in your PC:

print("C:\Users\Andy\Games")

This code looks perfectly fine at first sight, but if you run it, it would produce an error: invalid escape sequence in literal.

When Swift sees \U, it supposes that you are trying to escape character U, which is not a special character thus cannot be escaped.

Now that you've learned about its function, what type of character do you think \ is in Swift? It's a special character!

And like any special character, it can also be escaped by putting another \ in front of it (\\):

print("C:\\Users\\Andy\\Games")

The output of this code is:

C:\Users\Andy\Games

New line character:

Similarly, the escape sequence can be used to make an otherwise printable character serve a special function.

For example, the letter n can be printed normally, but adding a backslash before it (\n) will indicate the start of a new line:

print("Hello world!\nWhat a good day for coding!\n")
print("Let's have a blast!")

The output of this code is:

Hello world!
What a good day for coding!

Let's have a blast!

Notice the empty line after What a good day for coding! ?

That's one new line from the \n plus the new line that print() prints no matter what the message is.


Assignment
Follow the Coding Tutorial and let's escape some characters!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    SWIFT · STRINGS I

    Escaping Characters in Swift, explained

    Why strings need escaping

    A Swift string literal starts and ends with a double quote. That makes the double quote a special character: inside a string, it normally means "the string ends here". So this line doesn't work:

    print("I am John "the coder" Doe")
    

    Swift reads the string "I am John ", then finds the word the where it expects the end of the statement, and reports errors. To put a double quote inside a string, you escape it with a backslash.

    Escaping a double quote

    A backslash in front of a character tells Swift to treat the next character in a special way. \" stands for one literal double quote that does not end the string:

    print("I am John \"the coder\" Doe")
    print("After \"Coding 101\" we'll solve some problems")
    

    The output is:

    I am John "the coder" Doe
    After "Coding 101" we'll solve some problems
    

    The apostrophe in we'll needs no escape. Only the character that closes the string, the double quote, is special inside a double-quoted string.

    Escaping the backslash itself

    The backslash is special too, so a string can't contain a lone one. A file path shows the problem:

    print("C:\Users\Andy\Games")
    

    Swift tries to read \U as an escape sequence, and there is no such sequence. The compiler stops with error: invalid escape sequence in literal. To get a real backslash, write two:

    print("C:\\Users\\Andy\\Games")
    

    This prints C:\Users\Andy\Games. In the source, every \\ counts as one character in the string.

    The new line escape

    Escapes also work the other way: a backslash can give a plain letter a special meaning. \n is a line break.

    print("Hello world!\nWhat a good day for coding!\n")
    print("Let's have a blast!")
    

    The output has an empty line after the second sentence:

    Hello world!
    What a good day for coding!
    
    Let's have a blast!
    

    That empty line is the \n at the end of the first string plus the line break that print adds after any text.

    Common escape sequences in Swift

    WriteYou get
    \"a double quote
    \\a backslash
    \na new line
    \ta tab
    \'an apostrophe (allowed, rarely needed)
    \u{41}the Unicode character with that hex code, here A
    \(expression)the value of the expression, inserted into the string

    The last row is string interpolation, which also begins with a backslash. If you want the characters \( as text, write \\(.

    Ways to avoid escaping

    Swift has two other forms for text full of quotes or backslashes. A raw string puts one or more # signs around the quotes, and inside it a backslash is plain text:

    print(#"C:\Users\Andy"#)
    

    This prints C:\Users\Andy. A multi-line string uses three quotes, and a single " inside it needs no escape:

    print("""
    She said "hi"
    """)
    

    This prints She said "hi". The lesson's exercise uses regular escapes, so these are for later.

    The exercise

    The exercise has three prints, one step each:

    1. Quotes. Print I'll study "Coding 101" on AlgoCademy. The two double quotes around Coding 101 get a backslash; the apostrophe doesn't.
    2. Two lines from one print. Put \n between I will learn this and No matter what. The result is two lines from a single print.
    3. A path. Print C:\Users\Andy\notion with each backslash doubled. Without doubling, \U is an error, and \n in \notion would silently become a line break.
    print("I'll study \"Coding 101\" on AlgoCademy")
    print("I will learn this\nNo matter what")
    print("C:\\Users\\Andy\\notion")
    

    Key takeaways

    • A backslash starts an escape sequence inside a string literal.
    • Use \" for a double quote and \\ for a backslash.
    • \n is a new line, and print adds one more line break after the whole text.
    • An unknown sequence such as \U is a compile error.
    • Raw strings (#"..."#) and multi-line strings (""") reduce the need for escapes.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free