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

时间:2020-08-26 15:32:20

标签: swift delegates closures 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")
    }
}

这是什么原因? 根据我在网上发现的内容:由于没有初始化对象,因此自身不可用,这甚至意味着什么?

1 个答案:

答案 0 :(得分:3)

它的意思就是它的意思。

  • 如果您不说lazy,则用等号(=)尝试初始化sendingVC,这是ReceivingVC的实例属性,而ReceivingVC实例本身(self)正在初始化。在self初始化期间提及它是循环的,因此被禁止。

  • 通过说lazy,您是说:在初始化ReceivingVC实例(sendingVC之后的某个时间之前,不要初始化self-也就是说,当其他一些代码引用它时。这样就解决了问题,现在允许提及self