343max
343max

Reputation: 398

Subclassing UITableViewController in Swift

I subclassed a UITableViewController in Swift and added a custom initializer:

init(scheduleController: ScheduleController) {
    self.scheduleController = scheduleController
    super.init(style: UITableViewStyle.Plain)
    self.title = "Routes"
}

now when I start the app it crashes with:

fatal error: use of unimplemented initializer 'init(nibName:bundle:)' for class 'Shuttle_Plan.RoutesViewController'

How can I solve this without adding this initializer?

Upvotes: 2

Views: 1530

Answers (1)

matt
matt

Reputation: 534966

Maddening, isn't it? But the error message tells you what to do: if you are going to call super.init(style:), then you must also implement init(nibName:bundle:), even if all you do there is to call super:

override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
    super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil)
} 

This, however, raises the question of what to do about properties. Swift won't let you implement init(nibName:bundle:) unless it initializes all uninitialized properties.

  • One obvious solution is to make your properties Optionals; now the implementation shown above is legal. In init(scheduleController:), you will have to initialize your properties after calling super.init.

  • Less dramatically, make your property a var but not an Optional. Now initialize it multiple times: before super.init in all your initializers, and also after super.init in your init(scheduleController:).

None of those, however, are the solution I use in my own code. In my code, I do not call super.init(style:), as you are doing — I call super.init(nibName:bundle:) instead. This works because:

  • The default style is .Plain, which is what you want

  • Even if what you want is .Grouped, you can specify that in the associated nib file

The big advantage of this approach is that it permits your properties to be a non-Optional let, which is probably what you really would like to do.

Upvotes: 4

Related Questions