String literal as an argument to a function in println?

Is it possible to use a string literal as a function argument in a println statement.

func greetings(name: String) -> String {
    return "Greetings \(name)!"
}

      

What I was trying to do: (I tried to avoid quotes around Earthling.)

println("OUTPUT: \(greetings("Earthling"))")

      

You can also do this:

let name = "Earthling"
println("OUTPUT: \(greetings(name))")

      

And this works too:

println(greetings("Earthling"))

      

I tried to escape the quotes in the first example, but no luck, but that is not very important since this is the only test, I was just curious if there was a way to do this using a function call with a string literal as an argument in a print or println statement that contains other text.

+3


source to share


2 answers


From Apple docs:



The expressions you write in parentheses in an interpolated string cannot contain an unescaped double quote (") or backslash (\), and cannot contain a carriage return or line feed.

+1


source


The problem is, of course, not with println

, but with nesting quoted expressions in string literals. Thus,

let b = false
let s1 = b ? "is" : "isn't"
let s2 = "it \(b ? "is" : "isn't")" // won't compile

      

However NSLog as a one-liner "works really well here"



NSLog("it %@", b ? "is" : "isn't")

      

Note %@

, not %s

. Try the latter on the playground to see why.

0


source







All Articles