12

Is it possible to use a String/Character literal within string interpolation in Swift?

The language reference says:

The expression you write inside parentheses within an interpolated string cannot contain an unescaped double quote (") ...

That's a little fuzzy to me, since it seems to deliberately leave the loophole of escaped double quotes.

If I try:

println( "Output: \(repeat("H",20))" );

func repeat( char:Character, times:Int ) -> String {
    var output:String = "";
    for index in 1...times {
        output += char;
    }
    return output;
}

I get "Expected ',' separator".

Similarly, if I do the same thing, but escape the quotes, still no dice:

println( "Output: \(repeat(\"H\",20))" );

I suspect it's just not possible, and to be honest, no big deal -- I haven't found any example that I can't easily solve by doing a little work before the string interpolation, I guess I'm just looking for confirmation that it's just not possible.

Geoffrey Wiseman
  • 5,459
  • 3
  • 34
  • 52
  • `println("Output: " + repeat("H", 20) + "");`, maybe? the last `""` would not have been necessary to be added. – holex Aug 11 '14 at 15:39
  • Confirmed that @holex's solution works well. – Chris Wagner Aug 11 '14 at 19:15
  • Sure, that totally works -- but it's not string interpolation, it's just string concatenation. – Geoffrey Wiseman Aug 12 '14 at 17:53
  • 1
    Unfortunately I don't have a solution to your problem but when you use for in loop -> when your not using `index` simply do `for _ in 1...times` – borchero Dec 18 '14 at 21:24
  • possible duplicate of [escape dictionary key double quotes when doing println dictionary item in Swift](http://stackoverflow.com/questions/24024754/escape-dictionary-key-double-quotes-when-doing-println-dictionary-item-in-swift) – Mixaz Aug 27 '15 at 22:19
  • let value = repeat("H",20) println( "Output: \(value)"); @Narendra G – Narendra G Sep 25 '15 at 07:13

2 Answers2

3

It can be done starting in Swift 2.1: http://www.russbishop.net/swift-2-1

Prior to that, it wasn't possible.

Geoffrey Wiseman
  • 5,459
  • 3
  • 34
  • 52
0

I hope it's:

let strfunc = repeat("H",20) as string
println( "Output: \(strfunc)" );
  • 1
    Yeah, again, a perfectly fine solution to the problem I don't have. ;) There are lots of ways to get a repeated character into a string with or without interpolation. What I was really trying to verify is that there is no way to use a string literal within a Swift string interpolation expression. There doesn't seem to be. – Geoffrey Wiseman Sep 08 '14 at 03:40