我正在快速覆盖 UITableViewController
,其中我有两个必需的变量,它们是通过使用 self
的 weak
引用初始化的,因为这些用于实现 UITableViewDataSource
协议(protocol),需要 self
引用才能使用其 tableView
属性
class VideosListViewController: UITableViewController {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.datasourceOfflineVideos = ASDataSource(tableViewController: self)
self.datasourceOnlineVideos = ASDataSource(tableViewController: self)
}
// MARK: - Variables
var datasourceOnlineVideos:ASDataSource
var datasourceOfflineVideos:ASDataSource
}
现在的问题是它给我错误 Property not initialized at super.init call
这是预期的,如下所述:Error in Swift class: Property not initialized at super.init call .
Swift’s compiler performs four helpful safety-checks to make sure that two-phase initialization is completed without error
Safety check 1 A designated initializer must ensure that all of the “properties introduced by its class are initialized before it delegates up to a superclass initializer.
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11
所以我的问题是:
如果 swift 类中的实例变量需要像这里的 ASDataSource
类型变量一样初始化 self
引用,我该怎么做??
因为 swift 不允许我在初始化所有实例变量之前调用 super.init()
并且也不允许我使用 self
在调用 super.init()
init()
的初始化器中
目前我正在使用可选变量来解决这个问题。但出于学习目的,我想知道该怎么做。提前致谢:)
最佳答案
你只需要在你的初始化器中反转 super.init/properties 的顺序:
required init(coder aDecoder: NSCoder) {
self.datasourceOfflineVideos = ASDataSource(tableViewController: self)
self.datasourceOnlineVideos = ASDataSource(tableViewController: self)
super.init(coder: aDecoder)
}
实例属性首先出现,然后可以调用父类(super class)初始化器。但这在您的情况下是不可能的,因为您引用的是 self
。
这种情况下的解决方法是使属性隐式展开可选值:
var datasourceOnlineVideos:ASDataSource!
var datasourceOfflineVideos:ASDataSource!
由于可选值不需要初始化,您可以在调用 super.init
方法后安全地初始化它们。隐式解包后,您可以将它们用作任何其他非可选属性。
Apple 在多个类中使用了此模式,包括 UIViewController
:当您从 IB 添加 socket 时,组件属性始终声明为隐式展开。这是因为控件本身并未在初始化程序中实例化,而是在稍后阶段实例化。
关于ios - Swift 类 : Property not initialized at super. init 调用中的错误 - 如何初始化需要在其初始化参数中使用 self 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27028813/