So I need to pass data from ThirdVC to FirstVC so basically pass the delegate through the second protocol, and then the data through the First protocol I’m unsure how I would do it, this is UIKIT and Storyboard below is what I have so far, it works but I need it to do what I’m asking above.
protocol FirstCall {
func firstFunction(makerData: String,featuresData: [String])
}
class FirstVC: UIViewController, FirstCall {
var delegate: FirstCall?
@IBAction func buttonClicked(_ sender: Any) {
guard let SecondVC = storyboard?.instantiateViewController(identifier: "SecondVC") as? SecondVC else {return}
SecondVC.delegate = self
navigationController?.pushViewController(SecondVC, animated: true)
}
func firstFunction(makerData: String,featuresData: [String]) {
print(makerData)
print(featuresData)
}
}
protocol SecondCall {
func secondFunction(makerData: String,featuresData: [String])
}
class SecondVC: UIViewController, SecondCall {
var delegate: FirstCall?
@IBAction func buttonClicked(_ sender: Any){
guard let ThirdVC = storyboard?.instantiateViewController(identifier: "ThirdVC") as? ThirdVC else {return}
ThirdVC.delegate = self
navigationController?.pushViewController(ThirdVC, animated: true)
}
func secondFunction(makerData: String,featuresData: [String]){
delegate?.firstFunction(makerData: makerData,featuresData: featuresData)
}
}
class ThirdVC: UIViewController {
var delegate: SecondCall?
@IBAction func buttonClicked(_ sender: Any) {
self.navigationController?.popToRootViewController(animated: true)
delegate?.secondFunction(makerData: makerData,featuresData: featuresData)
}
}
2
Answers
Your approach works but it can get a little hairy if your protocols have a lot of methods.
Rather than defining two separate protocols where one is an intermediary, I’d just have a single protocol and use
typealias
to keep things clean.As you can see, the
SecondVC
doesn’t conform to any protocols. It just passes the delegate from theFirstVC
to theThirdVC
.For convenience:
The SecondVC shouldn’t know anything at all about the exchange. Even "passing the delegate along" from the first to the third should be outside of its responsibilities.
Have the navigation controller be the delegate of the view controllers and control its own affairs:
With something like the above, you can add/remove/rearrange view controllers without ever touching any specific view controller. Just update the navigation controller.