Danny Danny - 1 month ago 9
Swift Question

How to pass UIViewController to another class in Swift?

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

SomeViewController
class:

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

override func viewDidLoad() {
super.viewDidLoad()
header.setNavigationBar()
}
...
}


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?

Answer

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)
}()