6

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.

Team6Labs
  • 175
  • 3
  • 10

2 Answers2

8

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()
drewag
  • 93,393
  • 28
  • 139
  • 128
  • 2
    And you have to pass NSBundle.mainBundle() as bundle. Documentation says nil is ok, but atm you get error message if you trying to pass nil as bundle. – juniperi Jun 16 '14 at 03:45
  • 1
    @juniperi you just saved me many more hours of frustration. I was trying to instantiate an NSViewController passing nil for the bundle and I kept getting a "Could not find an overload for '__conversion' that accepts the supplied arguments" error. Passing NSBundle.mainBundle() fixes this. Thanks – mike Jun 17 '14 at 14:50
0

I had to make the initialization of the view controller a global constant in order for it to work throughout my app. After racking my brain, I found that it was working locally, so making it global (putting it outside the AppDelegate class. works for me without the "nil" error)

//global constant
let viewController = ViewController(nibName: "ViewController", bundle: NSBundle.mainBundle())

class AppDelegate: NSObject, NSApplicationDelegate {
    @IBOutlet var window: NSWindow

func applicationDidFinishLaunching(aNotification: NSNotification?) {

    //links and loads the view to the main window
    self.window.contentView.addSubview(viewController.view)
    viewController.view.frame = self.window.contentView.bounds

    //works locally and elsewhere as long as viewController is global!
    viewController.statusField.stringValue = "TESTING"
    println(viewController.statusField)

    } 
}
Goodtime
  • 111
  • 3
  • Also bundle: nil works too with the viewController constant is global. Apple's docs are not incorrect. This is on 10.9 anyways. nil loads the mainBundle according to the docs. and let controller = ViewController() also with it as a global with same class name. I've tested all three. – Goodtime Jul 08 '14 at 04:16