Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put double quotes into Swift String

Tags:

string

swift

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?

like image 480
Tom Shen Avatar asked Jun 08 '16 10:06

Tom Shen


3 Answers

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.

like image 52
Sergey Kalinichenko Avatar answered Oct 13 '22 12:10

Sergey Kalinichenko


extension CustomStringConvertible {
    var inspect: String {
        if self is String {
            return "\"\(self)\""
        } else {
            return self.description
        }
    }
}
let word = "Swift"
let s = "This is \(word.inspect)"
like image 31
webcpu Avatar answered Oct 13 '22 14:10

webcpu


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.

like image 8
Steve Madsen Avatar answered Oct 13 '22 13:10

Steve Madsen