如何解决错误 "Class appDelegate has no initializers"?

How do I resolve error "Class appDelegate has no initializers"?

我收到错误消息:

Class AppDelegate has no initializers

似乎不​​明白为什么。我正在关注 this tutorial。我是初学者,所以非常感谢任何帮助!

我的代码:

import UIKit

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    var centerContainer: MMDrawerController

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        _ = self.window!.rootViewController

        let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

        let centerViewController = mainStoryboard.instantiateViewController(withIdentifier: "ViewController") as! ViewController

        let leftViewController = mainStoryboard.instantiateViewController(withIdentifier: "LeftSideViewController") as! LeftSideViewController

        let leftSideNav = UINavigationController(rootViewController: leftViewController)
        let centerNav = UINavigationController(rootViewController: centerViewController)


        centerContainer = MMDrawerController(center: centerNav, leftDrawerViewController: leftSideNav)


        centerContainer.openDrawerGestureModeMask = MMOpenDrawerGestureMode.panningCenterView;

        centerContainer.closeDrawerGestureModeMask = MMCloseDrawerGestureMode.panningCenterView;

        window!.rootViewController = centerContainer
        window!.makeKeyAndVisible()

        return true
    }
}

尝试将 centerContainer 属性 更改为 可选 ,如下所示:

var centerContainer: MMDrawerController!

因此,它将用 nil 初始化,这应该足以消除您遇到的错误。 (顺便说一下,您不需要因此而更改其余代码。)

来自 The Swift Programming Language 本书:

Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state.

因为 centerContainer 不是可选的并且没有给定默认值,Swift 期望初始化函数给它一个。这里有一些可能的解决方案:

  1. 给它一个默认值。在这种情况下可能不切实际。
  2. 将其设为可选。会工作,但取决于它的使用方式可能会给您的代码添加很多不必要的解包。
  3. 使它成为一个隐式解包的可选项。这实质上是说 "I can't/don't want to give this a default value or set it in an initializer, but I will definitely be giving it a value before I use it for anything." 通常是此类事情的最干净的选项,请注意不要在代码后面的任何时候分配它 nil 否则事情会中断。

使您的 centerContainer 变量像 window 一样可选。在 swift 中,必须初始化所有属性。当您将 var 设置为可选时,您将其初始化为 nil.

var centerContainer: MMDrawerController?