Search code examples
swiftdelegatesclosuresself

Why is it not allowed to use self when creating a property using closure?


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

What is the reason behind this? From what i found online: Since the object is not initialised the self is not available, what does that even mean?


Solution

  • It means exactly what it says.

    • If you do not say lazy, then with your equal sign (=) you are trying to initialize sendingVC, an instance property of ReceivingVC, while a ReceivingVC instance itself (self) is being initialized. Mentioning self during its own initialization is circular so it's forbidden.

    • By saying lazy, you are saying: do not initialize sendingVC until sometime after the ReceivingVC instance (self) has been initialized — namely, when some other code refers to it. That solves the problem and mentioning self is now allowed.