为什么在使用闭包创建属性时不允许使用 self?


// Design Protocol
protocol SendDataDelegate {}
// Design Sender/Delegator
class SendingVC {
var delegate: SendDataDelegate?

deinit {
print("Delegator gone")
}
}
// Design Receiver/Delegate
class ReceivingVC: SendDataDelegate {
lazy var sendingVC: SendingVC = { // if i don't use lazy, i am not allowed to use self within the closure.
let vc = SendingVC()
vc.delegate = self // here
return vc
}()

deinit {
print("Delegate gone")
}
}

这背后的原因是什么? 从我在网上找到的:由于对象没有初始化,自我不可用,这甚至意味着什么?

它的意思正是它所说的。

  • 如果你不说lazy,那么你用你的等号(=)试图初始化sendingVC,这是接收VC的实例属性,而接收VC实例本身(self)正在初始化。在self自己的初始化过程中提及它是循环的,因此是禁止的。

  • 通过说lazy,你的意思是:不要初始化sendingVC,直到ReceptivingVC实例(self)初始化后的某个时间 - 即当其他代码引用它时。这解决了问题,现在允许提及self

最新更新