Created
January 23, 2015 14:50
-
-
Save pyrtsa/4d73d0943f86a977109a to your computer and use it in GitHub Desktop.
Quoted strings in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct QuotedString : Printable { | |
var string: String | |
init(_ string: String) { | |
self.string = string | |
} | |
var description: String { | |
let backslash: UnicodeScalar = "\\" | |
let quote: UnicodeScalar = "\"" | |
let hex: [UnicodeScalar] = ["0", "1", "2", "3", "4", "5", "6", "7", | |
"8", "9", "a", "b", "c", "d", "e", "f"] | |
var out = "" | |
out += "\"" | |
for u in string.unicodeScalars { | |
switch u { | |
case backslash: out += "\\\\" | |
case quote: out += "\\\"" | |
case "\n": out += "\\n" | |
case "\r": out += "\\r" | |
case "\t": out += "\\t" | |
case "\u{0}"..."\u{1f}", "\u{7f}": | |
out += "\\u{" | |
out.append(hex[Int(u.value) / 16]) | |
out.append(hex[Int(u.value) % 16]) | |
out += "}" | |
default: | |
out.append(u) | |
} | |
} | |
out += "\"" | |
return out | |
} | |
} | |
extension String { | |
var quote: QuotedString { return QuotedString(self) } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment