且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Swift 类中的错误:属性未在 super.init 调用中初始化 - 如何初始化需要在其初始化参数中使用 self 的属性

更新时间:2022-11-23 19:14:13

你只需要在初始化器中反转 super.init/properties 的顺序:

You just have to invert the order super.init/properties in your initializer:

 required init(coder aDecoder: NSCoder) {
    self.datasourceOfflineVideos = ASDataSource(tableViewController: self)
    self.datasourceOnlineVideos = ASDataSource(tableViewController: self)
    super.init(coder: aDecoder)
  }

先是实例属性,然后可以调用超类初始化器.但这在您的情况下是不可能的,因为您正在引用 self.

instance properties comes first, then the superclass initializer can be invoked. But that's not possible in your case, because you are referencing self.

这种情况下的解决方法是使属性隐式解包可选:

The workaround in this case is to make the properties implicitly unwrapped optionals:

var datasourceOnlineVideos:ASDataSource!
var datasourceOfflineVideos:ASDataSource!

由于可选项不需要初始化,您可以在调用 super.init 方法后安全地初始化它们.隐式解包后,您可以将它们用作任何其他非可选属性.

Since optionals don't need to be initialized, you can safely initialize them after the super.init method has been called. Being implicitly unwrapped, you use them as any other non optional property.

Apple 在多个类中使用此模式,包括 UIViewController:当您从 IB 添加一个插座时,组件属性总是被声明为隐式解包.那是因为控件本身不是在初始化程序中实例化的,而是在稍后阶段进行实例化.

This pattern is used by Apple in several classes, including UIViewController: when you add an outlet from IB, the component property is always declared as implicitly unwrapped. That's because the control itself is not instantiated in the initializer, but at a later stage.