Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

println

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

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

but the compiler is complaining about double quotes around current which represent the a key in my dictionary.

I tried escaping it with \ but it wasn't the right way.

Appreciate any help.

like image 432
Amir Rezvani Avatar asked Jun 03 '14 20:06

Amir Rezvani


People also ask

How do you escape a double quote in Swift?

To include quotes inside a string in Swift, escape the quote symbol with backslash character, i.e., place a backslash character before the double quote inside the string.

How do you escape quotes in a string?

You can put a backslash character followed by a quote ( \" or \' ). This is called an escape sequence and Python will remove the backslash, and put just the quote in the string. Here is an example. The backslashes protect the quotes, but are not printed.


2 Answers

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)") 
like image 186
Logan Avatar answered Sep 27 '22 20:09

Logan


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"]!) ) 
like image 25
Tom Kraina Avatar answered Sep 27 '22 20:09

Tom Kraina