3

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

  • try with optional init `let model: PagingTutorialModel?` – Özgür Ersil May 06 '16 at 12:00
  • 2
    No. Please don't switch to optionals for the sake of appeasing the compiler unless an optional is actually the correct representation of your data. – nhgrif May 06 '16 at 12:02
  • 1
    [Recommended reading regarding init with coder](http://stackoverflow.com/a/32108404/2792531). – nhgrif May 06 '16 at 12:02
  • 1
    Are you using storyboards? – nhgrif May 06 '16 at 12:02
  • I'm using storyboards yes. Funny how saying that out loud now makes everything seem so clear. If I am using storyboards then the controller is initialised when the scene is segue'd to ... so assigning to a let constant during initialisation is simply not possible unless we avoid storyboards all together. Would you mind posting this as an answer, and I will accept it. –  May 06 '16 at 12:38
  • You could implement the `NSCoding` protocol for your `PagingTutorialModel` class and call `init(coder:)` on it...see http://nshipster.com/nscoding/ – Aaron Rasmussen May 06 '16 at 13:24

2 Answers2

3

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.

nhgrif
  • 61,578
  • 25
  • 134
  • 173
1

The reason is, that in init?(coder:) you also need to set the model. Depending of you setup, one solution could be to trap in 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.

dasdom
  • 13,975
  • 2
  • 47
  • 58