Skip to content

Instantly share code, notes, and snippets.

@popmedic
Created March 26, 2021 14:15
Show Gist options
  • Save popmedic/917fd593f73137fc37a0933386f4f35a to your computer and use it in GitHub Desktop.
Save popmedic/917fd593f73137fc37a0933386f4f35a to your computer and use it in GitHub Desktop.
String Escape and Unescape
import Cocoa
let given = "{\n\t\"test\": \"this 😃 \\ \",\n\r\t\"\'testing\': 1\r\n}\\ \0 \\"
let expected = #"{\n\t\"test\": \"this 😃 \\ \",\n\r\t\"\'testing\': 1\r\n}\\ \0 \\"#
let expectedAscii = #"{\n\t\"test\": \"this \u{0001F603} \\ \",\n\r\t\"\'testing\': 1\r\n}\\ \0 \\"#
extension String {
private static let escapedChars = [
(#"\0"#, "\0"),
(#"\t"#, "\t"),
(#"\n"#, "\n"),
(#"\r"#, "\r"),
(#"\""#, "\""),
(#"\'"#, "\'"),
(#"\\"#, "\\")
]
var escaped: String {
self.unicodeScalars.map { $0.escaped(asASCII: false) }.joined()
}
var asciiEscaped: String {
self.unicodeScalars.map { $0.escaped(asASCII: true) }.joined()
}
var unescaped: String {
var result: String = self
String.escapedChars.forEach {
result = result.replacingOccurrences(of: $0.0, with: $0.1)
}
return result
}
}
print(expected == given.escaped)
print(expectedAscii == given.asciiEscaped)
print(given.escaped.unescaped == given)
print(expected.unescaped == given)
print(expected.unescaped.escaped == expected)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment