How to instantiate NSViewController in Swift?

Team6Labs picture Team6Labs · Jun 16, 2014 · Viewed 7.1k times · Source

My current Swift code of

         var appBundle = NSBundle.mainBundle()
         let controller: ViewController = ViewController.init(nibName:        "ViewController", bundle: nil)
    self.window.contentView.addSubview(controller.view)
    controller.view.frame = self.window.contentView.bounds

is getting two errors. One is "Expected member name or constructor call after type name" and the other is "() is not convertible to 'ViewController'. For reference, ViewController is a class that inherits from NSViewController.

Both of the errors are occurring on the second line of code. Thanks in advance.

Answer

drewag picture drewag · Jun 16, 2014

In swift you don't call init on classes to instantiate them. You leave out the init and just put the arguments right after the type name:

let controller = ViewController(nibName: "ViewController", bundle: NSBundle.mainBundle())

or, you shouldn't need to provide the nibName if it matches the name of the class:

let controller = ViewController()