Swift Three Double Quotes

Swift three double quotes

I assume you are using Xcode 8 or earlier. Multi line String Literals have been implemented in Swift 4. You can only use them with Xcode 9 Beta or by including the open source Swift 4 toolchain in your Xcode at the moment.

How to print double quotes inside ?

With a backslash before the double quote you want to insert in the String:

let sentence = "They said \"It's okay\", didn't they?"

Now sentence is:

They said "It's okay", didn't they?

It's called "escaping" a character: you're using its literal value, it will not be interpreted.


With Swift 4 you can alternatively choose to use the """ delimiter for literal text where there's no need to escape:

let sentence = """
They said "It's okay", didn't they?
Yes, "okay" is what they said.
"""

This gives:

They said "It's okay", didn't they?

Yes, "okay" is what they said.


With Swift 5 you can use enhanced delimiters:

String literals can now be expressed using enhanced delimiters. A string literal with one or more number signs (#) before the opening quote treats backslashes and double-quote characters as literal unless they’re followed by the same number of number signs. Use enhanced delimiters to avoid cluttering string literals that contain many double-quote or backslash characters with extra escapes.

Your string now can be represented as:

let sentence = #"They said "It's okay", didn't they?"#

And if you want add variable to your string you should also add # after backslash:

let sentence = #"My "homepage" is \#(url)"#

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.

Trim double quotation mark() from a string

trimmingCharacters(in is the wrong API. It removes characters from the beginning ({") and end (}) of a string but not from within.

What you can do is using replacingOccurrences(of with Regular Expression option.

let trimmedStr = str.replacingOccurrences(of: "[\"{\\]}]", with: "", options: .regularExpression)

[] is the regex equivalent of CharacterSet.

The backslashes are necessary to escape the double quote and treat the closing bracket as literal.


But don't trim. This is a JSON string. Deserialize it to a dictionary

let str = """
{"fileId":1902,"x":38,"y":97}
"""

do {
let dictionary = try JSONSerialization.jsonObject(with: Data(str.utf8)) as! [String:Int]
print(dictionary)
} catch {
print(error)
}

Or even to a struct

struct File : Decodable {
let fileId, x, y : Int
}

do {
let result = try JSONDecoder().decode(File.self, from: Data(str.utf8))
print(result)
} catch {
print(error)
}

Testing string for double quote characters in Swift

Depending on what you want to do:

let str = "Hello \"World\""

// If you simply want to know if the string has a double quote
if str.containsString("\"") {
print("String contains a double quote")
}

// If you want to know index of the first double quote
if let range = str.rangeOfString("\"") {
print("Found double quote at", range.startIndex)
}

// If you want to know the indexes of all double quotes
let indexes = str.characters.enumerate()
.filter { $1 == "\"" }
.map { $0.0 }
print(indexes)


Related Topics



Leave a reply



Submit