fuzzygoat
fuzzygoat

Reputation: 26223

String literal as argument for func within println?

Is there anyway to use a string literal as an argument to a function within a println statement.

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

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

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

You can alternatively do this:

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

And this works too:

println(greetings("Earthling"))

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

Upvotes: 3

Views: 105

Answers (2)

AlexT
AlexT

Reputation: 616

The problem is of course not with println but with the embedding of expressions with quotes 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 quite well here

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

Note %@, not %s. Try the latter in a playground to see why.

Upvotes: 0

zaph
zaph

Reputation: 112873

From the Apple docs:

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.

Upvotes: 1

Related Questions