3

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

1
  • change var text: String! to var text = "" Commented Aug 8, 2017 at 8:19

4 Answers 4

4

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" 
Sign up to request clarification or add additional context in comments.

2 Comments

Or text? += "! How r you?"
@Hamish You are right. I edited my answer.
2

You have to define the variable without the exclamation mark, like that :

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

Or shorter in function of the context:

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

Comments

2

You can get it by doing this

var text = "Hello!" as! String text = text + " How are you?" 

Hope it helps.

Comments

2

When handling exclamation points in Swift, you have to remember that trying to use ! to access a nonexistent optional value triggers a runtime error.

If an optional has a value, it is considered to be “not equal to nil”. So you have to check this before you can access to its underlying value:

if text != nil { text += "! How are you?" } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.