Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?' ?"

I have not been studying iOS or Swift for very long. With one of the latest Xcode updates, many of the apps I have made on my computer now appear to be using obsolete syntax.

Xcode talks us through converting it to new syntax but often that does not solve anything and I have a new problem. Here is code for one of the first app I made after the syntax has been converted. I am getting an error saying:

Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?' ?

I know this must be really simple but I don't know how to fix it. Here is my code:

@IBAction func findAge(sender: AnyObject) {
    var enteredAge = Int(age.text)
    if enteredAge != nil {
        var catYears = enteredAge! * 7
        resultLabel.text = "Your cat is \(catYears) in cat years"
    } else {
        resultLabel.text = "Please enter a whole number"
    }
}  
like image 293
HeeHeeHaha Avatar asked Oct 01 '15 16:10

HeeHeeHaha


1 Answers

The text property of a text label is an optional, you have to unwrap it before using it.

var enteredAge = Int(age.text!)

Even better:

if let text = age.text, let enteredAge = Int(text) {
    let catYears = enteredAge * 7
    resultLabel.text = "Your cat is \(catYears) in cat years"
} else {
    resultLabel.text = "Please enter a whole number"
}
like image 175
Eric Aya Avatar answered Oct 15 '22 07:10

Eric Aya