swift - "Value of optional type ' 字符串? ' not unwrapped; did you mean to use ' ! ' or ' ? ' ?"

标签 swift compiler-errors unwrap

我学习 iOS 或 Swift 的时间并不长。通过最新的 Xcode 更新之一,我在计算机上制作的许多应用程序现在似乎都在使用过时的语法。

Xcode 通过将其转换为新语法来告诉我们,但通常这并不能解决任何问题,而且我遇到了新问题。这是我在语法转换后制作的第一个应用程序之一的代码。我收到一条错误消息:

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

我知道这一定很简单,但我不知道如何解决。这是我的代码:

@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 属性是可选的,您必须在使用前将其解包。

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

关于swift - "Value of optional type ' 字符串? ' not unwrapped; did you mean to use ' ! ' or ' ? ' ?",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32892462/

相关文章:

c++ - 构造函数和g++编译配方的问题

rust - 有没有办法做unwrap_or_return一个错误(任何错误)

Scala:访问 optional 对象中的 optional 值

ios - 新手,核心数据实例化托管对象

swift - 访问枚举关联值作为可选

ios - Swift - 将背景图像添加到 Spritekit 场景

qt - 使用QT 5.8 Ubuntu构建新应用程序的问题

ios - 打开 UISplitViewController 到 Master View 而不是 Detail

python-3.x - RuntimeError : You must compile your model before using it

typescript - 有没有办法在 TypeScript 中递归解包函数类型?