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.
source to share
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.
source to share