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

不羁岁月 提交于 2019-12-05 17:30:29

问题


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"
    }
}  

回答1:


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"
}



回答2:


I tried that. But it still said the same thing. I have managed to fix it now. All I did was change device the simulator was displaying in. Just by fluke it I have got it working. Maybe it was because I was creating an iOS app and the iPad required different syntax.

Thank you for your reply! It is also ways useful to know different ways to do something.



来源:https://stackoverflow.com/questions/32892462/value-of-optional-type-string-not-unwrapped-did-you-mean-to-use-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!