"可选类型'String的值?没有包装;你是说用'!'要么 '?' ?” [英] "Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?' ?"
问题描述
我已经很长时间没有研究iOS或Swift了。借助最新的Xcode更新之一,我在计算机上制作的许多应用现在似乎都在使用过时的语法。
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通过将其转换为新语法来与我们对话但通常无法解决任何问题,而我又遇到了新问题。这是语法转换后我制作的第一个应用程序的代码。我收到一条错误消息:
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"
}
}
推荐答案
text
属性是可选的,使用前必须先将其打开。
The text
property of a text label is an optional, you have to unwrap it before using it.
var enteredAge = Int(age.text!)
甚至更好:
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"
}
这篇关于"可选类型'String的值?没有包装;你是说用'!'要么 '?' ?”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!