swift - 带感叹号的类属性仍作为可选返回

标签 swift option-type

我有课ScoreModel简化为:

class ScoreModel {
    var teamName : String!
}

可以将其放置在 Init() 中函数,因为它需要始终被设置,但这无助于我理解问题:

我有一个ScoreViewController : UIViewController我使用非可选 ScoreModel :

class ScoreViewController {
    var scoreModel : ScoreModel!
}

使用 prepareForSegue 传递。这一切都有效,但是当我想获取 teamName 时,它​​作为可选返回:

override func viewWillAppear(_ animated : Bool) {
    let name = scoreModel.teamName
    print(name) 
}

此输出:

Optional("teamNameEntered")

但是该变量在 ScoreModel 中标有感叹号,因此应该将其展开。为什么它仍然返回可选的?

编辑: 根据要求,prepareForSegue 方法:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destinationVC = segue.destination as? ScoreViewController {
        let scoreModel = self.scoreModel ?? ScoreModel()
        destinationVC.scoreModel = scoreModel
    }
}

最佳答案

首先,您的 scoreModel不是非可选的

You can declare optional variables using exclamation mark instead of a question mark. Such optional variables will unwrap automatically and you do not need to use any further exclamation mark at the end of the variable to get the assigned value.

根据您的情况,您可以为 teamName 分配可选值或非可选值。因此,如果它被分配了可选值,则需要将其解包才能使用。

关于swift - 带感叹号的类属性仍作为可选返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41515394/

相关文章:

swift:与 ‘UIPickerView’ 不同

java - 从嵌套可选检查中的列表中获取元素

c++ - 为什么我不能使用 std::Optional<T> (其中 T 是抽象的)?

java - 如何将单个元素列表转换为java 8可选

Swift 泛型 func 无法将类型的值转换为预期的参数类型

ios - PFObject 无法与匹配的 TextField 字符串(Parse、Swift、iOS、Xcode 7 Beta)一起正常工作

Swift 中的向量 SIMD 类型

arrays - 当 Int 值为 0 时从数组(tableView)中删除

java - 添加两个 Optional<BigDecimal> 数字的最优雅方法是什么

C++ 通过参数写入文件或控制台