18

I have tried to print it but it just by passes because it's an escaped character. e.g output should be as follows.

\correct
mfaani
  • 33,269
  • 19
  • 164
  • 293
Rahul Sonvane
  • 3,737
  • 7
  • 18
  • 21
  • Escape it again with another backslash: `"ab\\cd"` will give `"ab\cd"` – Eric Aya May 11 '15 at 14:53
  • 1
    It *is documented* in the Swift Book, and a link to the relevant chapter was provided in a comment to your previous question. – Martin R May 11 '15 at 15:13
  • 2
    Don't know why this question got those negative feedback, because it definitely helped me. The problem is, double backslash doesn't get shown in right panel when in playground – ramazan polat Feb 20 '16 at 16:03

4 Answers4

63

For that and also future reference:

\0 – Null character (that is a zero after the slash)
\\ – Backslash itself.  Since the backslash is used to escape other characters, it needs a special escape to actually print itself.
\t  – Horizontal tab
\n – Line Feed
\r  – Carriage Return
\”  – Double quote.  Since the quotes denote a String literal, this is necessary if you actually want to print one.
\’  – Single Quote.  Similar reason to above.
C-JARP
  • 1,028
  • 14
  • 16
19

Use the following code for Swift 5, Xcode 10.2

let myText = #"This is a Backslash: \"#
print(myText)

Output:

This is a Backslash: \

Now not required to add a double slash to use a single slash in swift 5, even now required slash before some character, for example, single quote, double quote etc.

See this post for latest update about swift 5

https://www.hackingwithswift.com/articles/126/whats-new-in-swift-5-0

AtulParmar
  • 4,358
  • 1
  • 24
  • 45
6
var s1: String = "I love my "
let s2: String = "country"
s1 += "\"\(s2)\""
print(s1)

It will print I love my "country"

aturan23
  • 4,798
  • 4
  • 28
  • 52
tania_S
  • 1,350
  • 14
  • 23
5

The backslash character \ acts as an escape character when used in a string. This means you can use, for example, double quotes, in a string by pre-pending them with \. The same also applies for the backslash character itself, which is to say that println("\\") will result in just \ being printed.

matthew.healy
  • 365
  • 2
  • 10
  • 1
    Thanks for the education, Eric, and sorry for such a noob mistake. I had been relying on Playground's output on the right, and never once have used that bottom panel. The lightbulb has now been lit. You must be a mod? I started another thread on this topic and it should probably die also. – Wayne Henderson Feb 05 '16 at 14:59