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.

6
  • println("Output: " + repeat("H", 20) + "");, maybe? the last "" would not have been necessary to be added. Commented Aug 11, 2014 at 15:39
  • Confirmed that @holex's solution works well. Commented Aug 11, 2014 at 19:15
  • Sure, that totally works -- but it's not string interpolation, it's just string concatenation. Commented Aug 12, 2014 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 Commented Dec 18, 2014 at 21:24
  • possible duplicate of escape dictionary key double quotes when doing println dictionary item in Swift Commented Aug 27, 2015 at 22:19

2 Answers 2

3

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

Prior to that, it wasn't possible.

Sign up to request clarification or add additional context in comments.

Comments

0

I hope it's:

let strfunc = repeat("H",20) as string
println( "Output: \(strfunc)" );

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.