robdashnash robdashnash - 2 years ago 100
Swift Question

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

Answer Source

View controllers cannot realistically have let values unless you're assign them a default value.

let foo = 3

The problem is, when we initialize view controllers from storyboards, iOS initializes the view controller with init(coder:). We don't have an opportunity to pass values in during initialization, so we cannot have let properties.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download