我有课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/