gpt4 book ai didi

ios - Swift:如何抑制特殊字符的解释并提供字符串文字

转载 作者:行者123 更新时间:2023-11-28 16:05:53 27 4
gpt4 key购买 nike

目标是序列化一个 Swift 对象,方法是将它转换为 JSON 对象,然后将 JSON 对象转换为可以通过网络传递并在另一端解码的 JSON 字符串。

问题是生成有效的 JSON 字符串。

换行符必须在 JSON 字符串中进行转义,但 Swift 会解释转义字符串中的特殊字符,而不是将字符串视为文字。

例如:

let a = "foobar\nhello\nworld"
let escapedString = a.replacingOccurrences(of: "\n", with: "\\n")

print(escapedString)

打印的是 foobar\nhello\nworld 而不是所需的 foobar\\nhello\\nworld

如何告诉 Swift 将字符串视为文字而不解释其中的特殊字符?

更新

正如 OOPer 所指出的,使用 debugPrint 显示 \\n 字符保持不变。

但是,当与 WKWebView 中的 evaluateJavaScript 配对时,\\n 字符会变成 \n ,这是根本问题。例如:

let script = "\(callback)(\'\(escapedString)\')"        
webView!.evaluateJavaScript(script) { (object: Any?, error: Error?) -> Void in
print("Done invoking \(callback)")
}

最佳答案

没有像 javascript 模板文字中那样的未转义字符串语法,这可能正是您正在寻找的;也许他们将来会添加它。不幸的是,您因此必须转义每个反斜杠,这有时看起来很奇怪,就像您的示例一样。

  //This is the same as `foobar\nhello\nworld` where each char is a literal
let a = "foobar\\nhello\\nworld"
let escapedString = a.replacingOccurrences(of: "\\n", with: "\\\\n")
//This outputs `foobar\\nhello\\nworld`
print(escapedString)

关于ios - Swift:如何抑制特殊字符的解释并提供字符串文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40294749/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com