VSB
VSB

Reputation: 10375

Swift: Provide default value inside string literal

I'm going to provide a default value for an optional String which is placed inside a String literal as a parameter (if I've used the right keywords!). I want to know how can I set a default value for it using "??" operator?

I think I should use escape characters before double quote but I don't know what is the right syntax. Here is my syntax which lead to error:

print ("Error \(response.result.error ?? "default value") ")
//------------------------ what should be ^here^^^^^^^^

Upvotes: 3

Views: 812

Answers (2)

LorenzOliveto
LorenzOliveto

Reputation: 7936

Just wrap it in parentheses:

print("Error \((response.result.error ?? "default value"))")

The cleaner way is to use @Alladinian answer and put the string in a variable before printing it

Upvotes: 5

Alladinian
Alladinian

Reputation: 35636

You have to literally substitute default value with your message.

No need to escape double quotes since you're inside \(<expression>) (More about Swift's string interpolation here)

If you need a cleaner approach then do it in two steps:

let msg = response.result.error ?? "whatever"
print("Error: \(msg)") 

Finally, if you want to print only non-nil errors (avoiding logs for responses that did not produce any errors) you could do:

if let error = response.result.error { print("Error: \(error)") }

Upvotes: 3

Related Questions