【问题标题】:escape dictionary key double quotes when doing println dictionary item in Swift在 Swift 中执行 println 字典项时转义字典键双引号
【发布时间】:2014-07-24 08:30:53
【问题描述】:

我一直在玩 Swift,但遇到了一个问题。 我有以下字典:

var locations:Dictionary<String,CLLocationCoordinate2D> = ["current":CLLocationCoordinate2D(latitude: lat, longitude: lng) ];

println("current locaition is \(locations["current"])")

但编译器抱怨 current 周围的双引号代表我字典中的 a 键。

我尝试使用\ 转义它,但方法不正确。

感谢任何帮助。

【问题讨论】:

标签: println swift


【解决方案1】:

Xcode 7.1+

从 Xcode 7.1 beta 2 开始,我们现在可以在字符串文字中使用引号。来自发行说明:

在字符串中插值的表达式现在可以包含字符串文字。例如,“My name is (attributes["name"]!)”现在是一个有效的表达式。 (14050788)

Xcode

我认为你不能那样做。

来自docs

您在插入字符串内的括号内编写的表达式不能包含非转义双引号 (") 或反斜杠 (\),也不能包含回车或换行。

你必须使用

let someVar = dict["key"]
println("Some words \(someVar)")

【讨论】:

  • 这个答案真是太糟糕了,但感谢@Logan 让它变得温柔!
  • 为什么有人会否决这个?你不能做你想做的事不是我的错,我真的引用了文档?
【解决方案2】:

我在插入字符串时也遇到过这个问题。我发现的最佳解决方案就是将其分成两行,如下所示:

let location = locations["current"]
println("current locaition is \(location)")

这可能是 Swift 的一个错误。根据我在文档中找到的内容,您应该可以使用 \ 来转义引号。

【讨论】:

  • 您可以使用转义引号,但不能在括号内使用。看我的回答。
  • 这让我很困惑。听起来你可以包含转义的双引号,但你用反斜杠转义它们,这是不允许的。
  • 我什至没有意识到这一点。它基本上是在说,除非你修复它,否则你不能这样做......但是,你不能修复它。
【解决方案3】:

Swift 不接受 \() 中的引号。因此需要将一行代码一分为二。

这是一个为中国读者展示示例的博客: http://tw.gigacircle.com/321945-1

【讨论】:

    【解决方案4】:

    您可以使用字符串连接代替插值:

    println("Some words " + dict["key"]! + " some more words.")
    

    请注意+ 标志周围的空格。

    更新:

    您可以做的另一件事是使用string format specifiers,就像在objective-c 时代一样:

    println( String(format: "Some words %@ some more words", dict["1"]!) )
    

    【讨论】:

      【解决方案5】:

      从 Swift 2.1 开始,您可以在插值中使用双引号。 println("current location is \(locations["current"])")

      【讨论】:

        猜你喜欢
        • 2017-01-17
        • 1970-01-01
        • 2017-06-26
        • 2015-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多