Search code examples
swiftoption-typestring-literals

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^^^^^^^^

Solution

  • 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