"Value of optional type" String? 'does not unfold, you wanted to use'! ' or '?'?"

I have not studied iOS or Swift for a very long time. With one of the latest Xcode updates, many of the applications I have made on my computer now use outdated syntax.

Xcode tells us converting it to a new syntax, but often it doesn’t solve anything, and I have a new problem. Here is the code for one of the first applications I made after syntax conversion. I get an error message:

The value of the optional type 'String?' does not unfold; you wanted to use '!' or '?'

I know this should be very 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" } } 
+5
source share
2 answers

The text property of the text label is optional, you need to expand it before use.

 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" } 
+10
source

I have tried this. But he still said the same thing. I managed to fix it now. All I did was change the device on which the simulator showed. Just on this matter it works for me. Perhaps this was because I was creating an iOS application, and the iPad required a different syntax.

Thanks for your reply! It is also useful to learn various ways to do something.

+1
source

Source: https://habr.com/ru/post/1232738/


All Articles