Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

include dictionary or array value in swift string with backslash notation [duplicate]

Tags:

swift

I'm testing out the playground for swift reading the ebook and am testing the backslash insert value into string thing.. wondering how I could do this with a dictionnary array, but it does not seem to like it.

var str="dictionary values are \(dict['mine'])"

this errors out. just wondering what the correct way to escape this would be, or should I just concatenate them in this case.

like image 432
cromestant Avatar asked Jun 04 '14 21:06

cromestant


2 Answers

Single quotes are not allowed as string delimiters in Swift. Additionally the string interpolation does not allow ‘unescaped double quote (") or backslash (\)’, cf. The Swift Programming Language

If you have the key as a constant (or variable) it will work:

let key = "mine"
let str = "dictionary values are \(dict[key])"

As an aside Swift encourages immutability for safety, you should always use let by default and only revert to var if you really need to.

like image 78
Nicholas H. Avatar answered Oct 28 '22 11:10

Nicholas H.


As far as I've been able to tell there isn't a way. You just have to break it up onto multiple line, like so:

let x = dict["mine"]
var str="dictionary values are \(x)"
like image 42
Mick MacCallum Avatar answered Oct 28 '22 11:10

Mick MacCallum