编写委托引用的不同选项 swift

Different options to write delegate reference swift

我试图创建一个函数委托来将数据从 MainViewController 传递到 SecondViewController。我设置协议:

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

我向 SecondViewController 添加了委托函数:

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

我将委托设置为 MainViewController:

weak var delegate: PassDataDelegate?

点击按钮时调用委托函数:

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

编写委托引用有两种选择:

选项 1

我在 MainViewController 中写了委托对 SecondViewController 的引用:

let secondViewController = SecondViewController()
self.delegate = secondViewController

它像我看的那样工作。

选项 2

我在SecondViewController中写:

let vc = MainViewController()
vc.delegate = self

问题是delegate还是nil,我不明白为什么。有什么提示吗?谢谢

选项 2

let vc = MainViewController()

您创建了一个新实例而不是真实呈现的实例,因此留下真实委托 = nil