0

How do you concatenate a backslash in swift?

i.e. "some string" + "\"

escaping the backslash gives me "some string\\" but I want "some string\"

Any ideas on how to accomplish this?

EDIT: I don't want to print out the string, I just want to concatenate the backslash. Escaping the backslash will store the string with two backslashes but I only want one.

EDIT 2: I think I figured it out. I used "\"" and that seems to work for me.

  • 5
    Have a look here: http://stackoverflow.com/questions/30170908/swift-how-to-print-character-in-a-string. So you'll need 3 backslashes in total – masterforker Feb 02 '16 at 23:11
  • If using an extra `"` somewhere fixed your code, then you were missing one somewhere else that was going to break things. It doesn't matter what you want to do with it - print it, use in a variable, whatever - the correct way to escape & concatenate is \\ as 3 people here have tried to tell you ... – mc01 Feb 03 '16 at 00:59

2 Answers2

0

The double backslash solution is correct (see console output in my small sample)

enter image description here

Stefan
  • 5,203
  • 8
  • 27
  • 51
0

Duplicate (Swift) how to print "\" character in a string? But..

If you're in a playground and type:

print("\\Hello, World")

... then yes both slashes and even a newline character appear in the results to the right as: \\Hello, World\n

but that's not the same as actual output.

If you open the debug console (Cmd-Shit-Y), or click the tiny eyeball icon that shows you the output, you'll see that there's only one \ and the escape works as expected.

For concantenation & string interpolation you could do...

var string = "some string"
print("\(string)\\") //prints "some string\"

Or...

string +="\\"
print(string) //also prints "some string\" 

Again, the right-column preview output is slightly different, so you have to look at the console. This is a somewhat confusing & annoying feature of Playgrounds. Not sure why they don't ensure both preview & console output are the same, or show the debug console by default.

enter image description here

Community
  • 1
  • 1
mc01
  • 3,750
  • 19
  • 24