How to print backslash “\” in Swift

It’s hard to print a backslash “\” in Swift if you don’t know how to escape from that character.

Look at the below code:

print("\")

It will throw an error: Unterminated string literal

There might be a lot of cases where you will see such an error like this.

But for now, just focus on why backslash is not printing in Swift. It’s always better to understand the actual reason of whatever is going on with your code.

In Swift, backslash \is an escape character. So it will check for the next character just after your single backslash.

If you try to print only a single backslash, there is no character after that escape character.

So there are some specific characters you can put just after that backslash. It makes an escape sequence.

Here are some examples:

\n – It will create a new line.
\r– It’s a carriage return.
\t – If you need some number of spaces, then it will work fine as it will act as a horizontal tab.
and finally, \\– It will print backslash.

Print backslash \ character easily in Swift

The easiest way is to write the below code:

print("\\")

Output:

\

Hey wait, there is another way to do so.

print(#"\"#)

Output:

\

So what’s going on here is simply making it to “\\\n

So the first double slash will print a single slash and the \n is always there by default no matter what you print through the print statement.

The use of # around the string is known as the Raw string.

Leave a Reply

Your email address will not be published. Required fields are marked *