如何解决为什么在使用闭包创建属性时不允许使用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
,这是ReceivingVC的实例属性,而ReceivingVC实例本身(self
)正在初始化。在self
初始化期间提及它是循环的,因此被禁止。 -
通过说
lazy
,您是说:在初始化ReceivingVC实例(sendingVC
之后的某个时间之前,不要初始化self
-也就是说,当其他一些代码引用它时。这样就解决了问题,现在允许提及self
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。