【问题标题】:Swift: how to suppress interpretation of special characters and provide string literalSwift:如何抑制特殊字符的解释并提供字符串文字
【发布时间】:2016-10-27 21:50:37
【问题描述】:

我们的目标是通过将 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)")
}

【问题讨论】:

    标签: ios json swift string


    【解决方案1】:

    没有像 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)
    

    【讨论】:

      【解决方案2】:

      也许您只是错误地解释了print 的输出。

      当您从print(escapedString) 获得foobar\nhello\nworld 时,escapedString 包含 20 个字符 -- f o o b a r \@9 987654334@llo\nwoorld。

      当包含在"s 之间时,这是一个有效的 JSON 字符串。

      如果你想用类似字符串文字的表示法检查转义的结果,你可以使用debugPrint:

      let a = "foobar\nhello\nworld"
      let escapedString = a.replacingOccurrences(of: "\n", with: "\\n")
      
      print(escapedString) //->foobar\nhello\nworld
      debugPrint(escapedString) //->"foobar\\nhello\\nworld"
      

      对于更新

      当与evaluateJavaScript一起使用时,你最好想想什么是JavaScript的正确代码,如果你想在JavaScript中表示一个JSON转义字符串,你应该写在.js文件中(或<script>...</script>):

      someFunc('foobar\\nhello\\nworld');
      

      所以,你可能需要这样写:

      let a = "foobar\nhello\nworld"
      let escapedForJSON = a.replacingOccurrences(of: "\n", with: "\\n")
      //In actual code, you may need a little more...
      let escapedForJavaScriptString = escapedForJSON.replacingOccurrences(of: "\\", with: "\\\\")
      
      let script = "\(callback)(\'\(escapedForJavaScriptString)\')"
      webView!.evaluateJavaScript(script) { (object: Any?, error: Error?) -> Void in
          print("Done invoking \(callback)")
      }
      

      【讨论】:

      • 这是一个很好的观点,所以也许应该在 evaluateJavaScript. 内部使用时在 \\n 消失的地方发布更多代码
      • 更新问题,希望您能就根本问题提供反馈
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-16
      • 1970-01-01
      相关资源
      最近更新 更多