Home > Software engineering >  Why I cannot use \ or backslash in a String in Swift?
Why I cannot use \ or backslash in a String in Swift?

Time:02-15

I have a string like this in below and I want replace space with backslash and space.

let test: String = "Hello world".replacingOccurrences(of: " ", with: "\ ")
print(test)

But Xcode make error of :

Invalid escape sequence in literal

The code in up is working for any other character or words, but does not for backslash. Why?

CodePudding user response:

Backslash is used to escape characters. So to print a backslash itself, you need to escape it. Use \\.

CodePudding user response:

For Swift 5 or later you can avoid needing to escape backslashes using the enhanced string delimiters:

let backSlashSpace = #"\ "# 

If you need String interpolation as well:

let value = 5
let backSlashSpaceWithValue = #"\\#(value) "#
print(backSlashSpaceWithValue) //  \5

You can use as many pound signs as you wish. Just make sure to mach the same amount in you string interpolation:

let value = 5
let backSlashSpaceWithValue = ###"\\###(value) "###
print(backSlashSpaceWithValue) //  \5

Note: If you would like more info about this already implemented Swift evolution proposal SE-0200 Enhancing String Literals Delimiters to Support Raw Text

  • Related