Posts tagged #optionals

Swift - Cannot use += operator with String! from UITextField or UITextArea - Implicitly Unwrapped Optional

I'm guessing this is a bug (submitted bug #, but if it isn't, you'll be surprised to learn that in Xcode Version 6.1.1 you cannot append to a String from a UITextView or UITextField.

The problem is that both the UITextField and the UITextView are using an implicitly unwrapped optional String (String!) as the type. This is messing up the +=, so you either have to break apart the statement (defeating the purpose of +=). Or you have do a force unwrap before the +=.

If you don't you'll get a strange Swift Compiler Error stating that 'String!' is not identical to 'UInt8'

var numberString: String! = "0"
numberString = numberString + "2"

numberString! += "1"
numberString += "1" //'String!' is not identical to 'UInt8'

var textView = UITextView()
textView.text += "More text" //'String!' is not identical to 'UInt8'

var textField = UITextField()
textField.text += "Even more text" //'String!' is not identical to 'UInt8'
Posted on December 11, 2014 and filed under iOS 8, swift .