Tom Shen
Tom Shen

Reputation: 2028

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\""
    dealWithString(string)
}

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?

Upvotes: 15

Views: 10079

Answers (3)

Steve Madsen
Steve Madsen

Reputation: 13791

Newer versions of Swift support an alternate delimiter syntax that lets you embed special characters without escaping. Add one or more # symbols before and after the opening and closing quotes, like so:

#"String with "Double Quotes""#

Be careful, though, because other common escapes require those extra # symbols, too.

#"This is not a newline: \n"#
#"This is a newline: \#n"#

You can read more about this at Extended String Delimiters at swift.org.

Upvotes: 10

webcpu
webcpu

Reputation: 3422

extension CustomStringConvertible {
    var inspect: String {
        if self is String {
            return "\"\(self)\""
        } else {
            return self.description
        }
    }
}
let word = "Swift"
let s = "This is \(word.inspect)"

Upvotes: 4

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726539

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.

Upvotes: 9

Related Questions