Search code examples
swiftspecial-charactersswift-playgroundescaping

How to store \"> in a Swift string?


I'm trying to store \"> in a string. Theoretically, "\\" should print \ and "\"" does print ". However, when I try to print \ in a string using \ the output is a double forward slash:

var str = "\">" 
// ">
var str2 = "\\"
// \\ 
var str3 = "\\\">"
// \\">
var str4 = "\\">"
// escapes after quotation mark (error)

Solution

  • The answer is str3. See for example:

    var str3 = "\\\">"
    str3.characters.forEach {
        print($0)
    }
    

    \
    "
    >

    It does not matter what str3 itself outputs in Xcode since Xcode can decide how to display strings. E.g. it decides to display the escaping character of \. It does not display the escape in front of " because in Playground for example the inner " is already differently colored that the " that actually delimit the string:
    enter image description here