Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data between two ViewController using closure

I want to know how to pass data using closure. I know that there are three types of data pass approaches:

  • delegate

  • Notification Center

  • closure

I want proper clarification of closure with an example.

like image 972
Sagar vaishnav Avatar asked Aug 31 '25 01:08

Sagar vaishnav


1 Answers

Well passing data with blocks / closures is a good and reasonable approach and much better than notifications. Below is the same code for it.

First ViewController (where you make object of Second ViewController)

 @IBAction func push(sender: UIButton) {
        let v2Obj = storyboard?.instantiateViewControllerWithIdentifier("v2ViewController") as! v2ViewController
        
        v2Obj.completionBlock = {[weak self] dataReturned in
            //Data is returned **Do anything with it **
            print(dataReturned)
        }
        navigationController?.pushViewController(v2Obj, animated: true)
        
    }

Second ViewController (where data is passed back to First VC)

import UIKit
typealias v2CB = (infoToReturn :String) ->()
class v2ViewController: UIViewController {
        var completionBlock:v2CB?
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func returnFirstValue(sender: UIButton) {
        guard let cb = completionBlock else {return}
        cb(infoToReturn: "any value")
    }
    
}
like image 120
ankit Avatar answered Sep 02 '25 13:09

ankit