Danny Danny - 5 months ago 29
Swift Question

How to pass UIViewController to another class in Swift?

How to pass UIViewController to another class in Swift?
I have


class RidingViewController: UIViewController {
fileprivate let header = RidingViewHeader(controller: self)

override func viewDidLoad() {

And I want to separate some code and to set up its header in the another class. I've created this class

class RidingViewHeader {

var controller: UIViewController
let navigationBar= UINavigationBar()
let navigationItem = UINavigationItem()

init(controller: UIViewController) {
self.controller = controller

In this case I get an error:
Cannot convert value of type '(NSObject) -> () -> UIViewController' to expected argument type 'UIViewController'

What is the better way of doing it?


You can't access self until the view controller has been initialized. You could make it a lazy variable:

fileprivate lazy var header: RidingViewHeader = {
    return RidingViewHeader(controller: self)