extension String {
func jsonEncoded() -> String {
var result = ""
for c in self {
switch c {
case "\"":
result.append("\\\"")
case "\n":
result.append("\\n")
case "\r":
result.append("\\r")
case "\t":
result.append("\\t")
case "\\":
result.append("\\\\")
default:
result.append(c)
}
}
return result
}
}
Yes, AI recommends the way too. However, I need to fill out a structure and then call JSONEncoder. Although Swift has a similar structure anatomy to Rust, I didn’t learned it yet. BTW I didn’t use Serde in Rust also, preferring the old fashion way - from parts.
var jsonEncoded: String {
reduce(into: "") { result, c in
let symbol = switch c {
case "\"": "\\\""
case "\n": "\\n"
case "\r": "\\r"
case "\t": "\\t"
case "\\": "\\\\"
default: String(c)
}
result.append(symbol)
}
}
var jsonEncoded: String {
map {
switch $0 {
case "\"": "\\\""
case "\n": "\\n"
case "\r": "\\r"
case "\t": "\\t"
case "\\": "\\\\"
default: String($0)
}
}.joined()
}
but I wouldn't be surprised if this has worse memory / runtime characteristics compared to above.
Yep, I meant you'd put that snippet into extension String { ... }
Do you want to implement this quickly or do you want it to work quickly? Equally important consideration – how long are the strings in question – it won't make sense to invest into a more complicated algorithm if strings are known to be short where the complex algorithm will not be able to show it's full potential (and will be slower).
If the former ("do it in under one minute") – just compare the newly accumulated string and the original string and only return the new string if the two are different. Slightly more optimal but still trivial to write would be maintaining a boolean variable that you'd set in case of encountering a special character, then when it comes to return either return the new string or the original string based on that variable.
If the latter ("make it work fast") – it's more complicated and longer to implement, I'd suggest to have two string indices (left and right) in addition to a boolean variable. While stepping through the string you advance the right index and check the character preceding it, if it's a special character then set the bool flag and append all characters within left ... right to the newly accumulated string, and adjust both indices to point to the current location. Otherwise (no special character case) just continue with the loop increasing the right index to point to the next location in the string. When it comes to return - check the boolean flag, if set then return the newly accumulated string otherwise return the original string.
Generally, the interest was how Swift good for server side applications? You perfectly resolved the question. Anyway, I like Swift and probably will use it for personal applications after I buy iPhone.