Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why '+=' does not work for implicitly unwrapped optionals? [duplicate]

When updating the text of UITextView, I found textView.text += "..." does not work. The compiler warned me that "Binary operator '+=' cannot be applied to operands of type 'String!' and 'String'". It seems that I must append an exclamatory mark after textView.text.

However, if I expanded it to textView.text = textView.text + "...", it worked. I wonder whether it is designed as this or I misunderstood something?

like image 594
yzyzsun Avatar asked Oct 30 '22 14:10

yzyzsun


1 Answers

Implicitly unwrapped optional is still an Optional and it's different from type that it wraps. So you need to define operator:

func +=(inout l: String!, r: String) {
    l = (l ?? "") + r
}

var a: String! = "a"
var b: String = "b"

a += b // "ab"
like image 70
mixel Avatar answered Jan 04 '23 14:01

mixel