Tom Shen Tom Shen - 4 months ago 16x
Swift Question

How to put double quotes into Swift String

I am writing some codes that deals with string with double quote in Swift. Here is what I've done so far:

func someMethod {
let string = "String with \"Double Quotes\""

func dealWithString(input: String) {
// I placed a breakpoint here.

When I run the codes the breakpoint stopped there as usual but when I input the following into the debugger:

print input

This is what I get:

(String) $R0 = "String with \"Double Quotes\""

I got this string with the backslashes. But if I tried to remove the backslashes from the source, it will give me compile error. Is there a workaround for this?


You are doing everything right. Backslash is used as an escape character to insert double quotes into Swift string precisely in the way that you use it.

The issue is the debugger. Rather than printing the actual value of the string, it prints the value as a string literal, i.e. enclosed in double quotes, with all special characters properly escaped escaped.

If you use print(input) in your code, you would see the string that you expect, i.e. with escape characters expanded and no double quotes around them.