Home > OS >  Swift - For an array of strings, how to remove backslash "\" escape
Swift - For an array of strings, how to remove backslash "\" escape

Time:12-06

I'm trying to figure out how to remove the backslash "\" escape character in an array of strings, for words with an apostrophes. Swift automatically adds an escape in strings that have apostrophes, in an array.

For example, suppose I have this:

var tempArray = [String]()
tempArray.append("test")
tempArray.append("one")
tempArray.append("test's")
tempArray.append("right")
print(tempArray[2]) //Prints: test's
print(tempArray) //Prints: ["test", "one", "test\'s", "right"]

As you can see, one of the strings I append into the array is "test's", which has an apostrophe. When I just print this element I get "test's", which is fine. However, when I print the entire array I get "test\'s". I don't want to automatically insert a backslash to "test's"

I would ultimately like to store tempArray as a JSON string in a SQLite database. So If I store this array as is, the backslash "\" will break the JSON.

Why does Swift insert backslashes into an array of strings (It doesn't seem to do so for regular string variables)? And how do I ensure that tempArray prints and stores as a proper JSON string?

I've tried to play with different approaches but have not been able to find a solution. Any help is appreciated. Thank you.

CodePudding user response:

What you need is to encode your array of strings. You can use JSONSerialization method or JSONEncoder. Nowadays you are likely supposed to use Codable protocol only (JSONEncoder/JSONDecoder):

var tempArray = [String]()
tempArray.append("test")
tempArray.append("one")
tempArray.append("test's")
tempArray.append("right")
print(tempArray)
do {
    let jsonData = try JSONEncoder().encode(tempArray)
    let jsonString = String(data: jsonData, encoding: .utf8) ?? ""
    print(jsonString)
} catch {
    print(error)
}

This will print:

["test", "one", "test\'s", "right"]
["test","one","test's","right"]

  • Related