Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value of optional type String? not unwrapped

Tags:

ios

swift

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
    }
like image 530
Insane Avatar asked Sep 12 '14 01:09

Insane


1 Answers

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
    }
}
like image 195
ZYiOS Avatar answered Oct 20 '22 19:10

ZYiOS