Insane Insane - 4 months ago 30
Swift Question

Value of optional type String? not unwrapped

I am just not able to unwrap

else
block. xCode gives me options to "Fix it with ! and ??", which sadly does not fix the issue either.
I get this error in xCode:
Value of optional type 'String?' not unwrapped; did you mean to use ! or ??

@IBAction func buttonTapped(theButton: UIButton) {
if answerField.text == "0" {
answerField.text = theButton.titleLabel?.text
} else {
answerField.text = answerField.text + theButton.titleLabel?.text
}

Answer

Because theButton.titleLabel?.text it not unwrapped.

You can use

 answerField.text  = answerField.text + (theButton.titleLabel?.text ?? "")

or

if answerField.text == "0" {
    answerField.text = theButton.titleLabel?.text
} else {
    if let txt = theButton.titleLabel?.text {
        answerField.text  = answerField.text + txt
    } else {
        answerField.text  = answerField.text
    }
}