Why does "+ =" not work for implicitly deployed options?

When updating a UITextView text, I found that textView.text += "..." not working. The compiler warned me that the binary operator + = cannot be applied to operands of type String! "and" String ". It seems that I should add an exclamation mark after textView.text .

However, if I expanded it to textView.text = textView.text + "..." , it worked. I wonder if it was designed that way, or did I misunderstand something?

+5
source share
2 answers

The implicitly expanded optional parameter is still Optional and is different from the type it wraps. Therefore, you need to define an operator:

 func +=(inout l: String!, r: String) { l = (l ?? "") + r } var a: String! = "a" var b: String = "b" a += b // "ab" 
+2
source

Both are different when u executes textField.text + = "text", means that u adds another line to it. But when you use textField.text = textField.text + "text", then you add 2 lines and set to textField.

0
source

Source: https://habr.com/ru/post/1237311/


All Articles