Error in Swift class: Property not initialized at super.init call - How to initialize properties which need use of self in their initializer parameter

后端 未结 1 1544
别那么骄傲
别那么骄傲 2020-12-06 13:35

I am overriding a UITableViewController in swift, in which I have two required variables which are initialized by using a weak reference of s

相关标签:
1条回答
  • 2020-12-06 14:03

    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)
      }
    

    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!
    

    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.

    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.

    0 讨论(0)
提交回复
热议问题