1

Can one use (escaped) double quotes in a string interpolation in Swift?

let s = "\(n) \(capitalized ? "H" : "h")ours"

produces "Unexpected '"' character in string interpolation (which is in line with a NOTE in the documentation), but I've also had no success with several attempts at escaping the inner double quotes so far.

So can one use (escaped) double quotes in string interpolations and if so how?

Drux
  • 11,992
  • 13
  • 66
  • 116
  • Possible duplicate of [Can you use string/character literals within Swift string interpolation?](http://stackoverflow.com/questions/25245820/can-you-use-string-character-literals-within-swift-string-interpolation) – Cœur Mar 17 '17 at 04:27

3 Answers3

2

Since Swift 2.1 we can use double quotes when interpolating, so the original code now works.

Antonio Favata
  • 1,891
  • 1
  • 15
  • 13
1

@Daniel answer is good, but in your case you could use the builtin capitalizedString method.

let s =  "hours".capitalizedString

or

let s =  "\n hours".capitalizedString

This method capitalize the first letter of each word. Edit:

let s =  (capitalized ? "hours".capitalizedString : "hours")
LastMove
  • 2,482
  • 1
  • 15
  • 25
  • But didn't he wanted to capitalize the string according the capitalized parameter? Your solution always capitalizes it. – Dániel Nagy Jan 27 '15 at 09:29
0

You can escape characters with the \, but I think you couldn't use the ternary operator this way in string interpolation. So I would suggest to put capitalized ? "H" : "h" in a variable, and then it will work.

UPDATED

You can use the ternary operator in string interpolation, but you cannot use string literals in there, so you should put the whole expression to a variable, or the upper and the lowercase h.

Dániel Nagy
  • 11,815
  • 9
  • 50
  • 58
  • 1
    The note in the documentation says: "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." This seems to suggest that *escaped* double quotes and backslashes may be allowed, but then perhaps they are not ... – Drux Jan 27 '15 at 09:30
  • @Drux Yes, it suggests that, but I do belive that is wrong in the documentation and they mean "inside double quotes" not "inside parentheses", because you can put escaped " between double qoutes, but cannot put a single one. – Dániel Nagy Jan 27 '15 at 09:37