Search code examples
swiftstring-concatenation

How to concatenate optional String in SWIFT


I want to concatenate a string, and I do this:

var text: String!
....
text = "hello" 
text += "! How r you?"

But I got the following error:

cannot convert value of type 'String!' to expected argument type 'inout String' text += "!" ^~~~

How can I fix it? Thanks


Solution

  • If you want to append something to an optional, but only if it's not nil, you should put a question mark after the variable's name.

    text? += "appended text"