Search code examples
swiftxcodeoption-typeuiapplicationdelegate

Different options to write delegate reference swift


I was trying to create a function delegate to pass data from MainViewController to SecondViewController. I set the protocol:

protocol PassDataDelegate: AnyObject {
    func passData(data: [String])
}

I added the delegate function to the SecondViewController:

func passData(data: [String]) {
   //Pass Data
}

I set delegate to MainViewController:

weak var delegate: PassDataDelegate?

Here when the button is tapped the delegate function is called:

@objc func buttonTapped() {
    guard let vcdelegate = delegate else {return}
    vcdelegate.passData(data: data)
}

There are two options to write the delegate reference:

Option 1

I write in MainViewController the reference of delegate to the SecondViewController:

let secondViewController = SecondViewController()
self.delegate = secondViewController

It works like I aspected.

Option 2

I write in SecondViewController:

let vc = MainViewController()
vc.delegate = self

The problem is that delegate is still nil, I don't understand why. Any hints? Thanks


Solution

  • In option 2

    let vc = MainViewController()
    

    you create a new instance other than the real presented one so leaving the real delegate = nil