简体   繁体   中英

Cannot assign value of type 'Class' to type '[Class]'

I'm setting up my first Swift project, and I'm currently getting this error:

Cannot assign value of type 'UIViewController' to type '[UIViewController]'

I have a sneaking suspicion this is related to all this ? ! business...

I thought I had the ? s figured out and enough of a working understanding of the ! s to get started, but when I started looking into app delegate initialization I got confused by the way they're using the ! s. This is what I've got so far in my didFinishLaunchingWithOptions method:

    self.window = UIWindow(frame: UIScreen.mainScreen().bounds);
    self.navCtrlr = UINavigationController();
    self.rootVC = RootViewController(nibName: nil, bundle: nil);
    self.navCtrlr!.viewControllers = self.rootVC! as UIViewController; ****
    self.window!.rootViewController = self.rootVC;
    self.window?.makeKeyAndVisible();

Line 4 (with the ****) is the one with the problem. Initially I was using self.rootVC as UIViewController without the ! , but I got an error that asked me to add the ! , so I did. Now I get the error I'm having now. This is what my class properties look like:

var window: UIWindow?;
var navCtrlr = UINavigationController?();

var rootVC: RootViewController?;

The UINavigationController instantiation confuses me as well, to be honest... The reason we use the ? is because we want the variable to be able to contain nil, and to not have to define it before we create the object, right? So why the () at the end? But I digress.

What is the difference between 'UIViewController' and '[UIViewController]' , and what can I do to make this error go away?

Try

self.navCtrlr!.viewControllers = [self.rootVC! as UIViewController];

[UIViewController] is Array in swift

Besides,I think the rootViewController is the navigationController,so

  self.window = UIWindow(frame: UIScreen.mainScreen().bounds);
  self.rootVC = RootViewController(nibName: "youNibName", bundle: nil);
  self.navCtrlr = UINavigationController(rootViewController: self.rootVC!);
  self.window!.rootViewController = self.navCtrlr;
  self.window?.makeKeyAndVisible();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM