[英]Swift: How to initialise a let constant in a UIViewController subclass
I want the model to be passed in by the implementing developer and I want that to be mandatory. 我希望模型由实现开发人员传入,我希望它是强制性的。
let model: PagingTutorialModel
init(withModel model: PagingTutorialModel) {
self.model = model
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
Error: Property 'self.model' not initialised at super.init call 错误:属性'self.model'未在super.init调用时初始化
View controllers cannot realistically have let
values unless you're assign them a default value. 视图控制器实际上let
值,除非您为它们分配默认值。
let foo = 3
The problem is, when we initialize view controllers from storyboards, iOS initializes the view controller with init(coder:)
. 问题是,当我们从故事板初始化视图控制器时,iOS使用init(coder:)
初始化视图控制器。 We don't have an opportunity to pass values in during initialization, so we cannot have let
properties. 我们没有机会在初始化期间传递值,因此我们不能let
属性。
The reason is, that in init?(coder:)
you also need to set the model. 原因是,在init?(coder:)
你还需要设置模型。 Depending of you setup, one solution could be to trap in init?(coder:)
: 根据您的设置,一个解决方案可能是在init?(coder:)
陷阱init?(coder:)
:
required init?(coder aDecoder: NSCoder) {
fatalError("Not implemented")
}
But doing so, you can't initialize this view controller from a storyboard. 但这样做,您无法从故事板初始化此视图控制器。 But in my opinion Storyboards are only for prototyping. 但在我看来,故事板只适用于原型设计。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.