escape dictionary key double quotes when doing println dictionary item in Swift

前端 未结 5 759
鱼传尺愫
鱼传尺愫 2020-11-30 08:51

I\'ve been playing around with Swift, and just came across an issue. I have the following Dictionary in:

var locations:Dictionary

        
相关标签:
5条回答
  • 2020-11-30 08:51

    Xcode 7.1+

    Since Xcode 7.1 beta 2, we can now use quotations within string literals. From the release notes:

    Expressions interpolated in strings may now contain string literals. For example, "My name is (attributes["name"]!)" is now a valid expression. (14050788)

    Xcode <7.1

    I don't think you can do it that way.

    From the docs

    The expressions you write inside parentheses within an interpolated string cannot contain an unescaped double quote (") or backslash (\), and cannot contain a carriage return or line feed.

    You'd have to use

    let someVar = dict["key"]
    println("Some words \(someVar)")
    
    0 讨论(0)
  • 2020-11-30 08:56

    I've had this problem too with interpolating strings. The best solution I found was just to split it into two lines like so:

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

    It may be a bug with Swift. From what I found in the docs, you should be able to use \ to escape quotes.

    0 讨论(0)
  • 2020-11-30 08:56

    Since Swift 2.1 you can use double quotes on interpolation. println("current location is \(locations["current"])")

    0 讨论(0)
  • 2020-11-30 09:00

    Swift doesn't accept quote in \(). Therefore you need to separate the one-line code into two.

    Here is a blog showing example for Chinese readers: http://tw.gigacircle.com/321945-1

    0 讨论(0)
  • 2020-11-30 09:09

    You can use string concatenation instead of interpolation:

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

    Just mind the spaces around the + signs.

    UPDATE:

    Another thing you can do is to use string format specifiers the same way how it was done back in the objective-c days:

    println( String(format: "Some words %@ some more words", dict["1"]!) )
    
    0 讨论(0)
提交回复
热议问题