How to put double quotes into Swift String

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.


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.


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

Tags:

String

Swift