Sending data between ViewControllers in Swift

Posted By : Akshay Luthra | 07-Jun-2016

This blog will help you to solve the very common issue that every developer (being it an iOS or some other technology developer) face, i.e, what is the optimum way of passing data from one screen to another.

 

As far as the swift is concern, I found that the "Delegation" is the best approach to pass the data between View Controllers.

Delegation is a design pattern that enables a class or structure to hand off (or delegate) some of its responsibilities to an instance of another type. This design pattern is implemented by defining a protocol that encapsulates the delegated responsibilities, such that a conforming type (known as a delegate) is guaranteed to provide the functionality that has been delegated.

 

 

To pass data from ParentViewController to ChildViewController :

 

In ParentViewController :

Using Segue -

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
    let goToChildView = segue.destinationViewController as ChildViewController 
    goToChildView.dataToPass = data
    goToChildView.delegate = self  // don't forget to add this line
}
 

 

Without Using Segue -

let goToChildView = storyboard?.instantiateViewControllerWithIdentifier("childView") as ChildViewController
goToChildView.dataToPass = data
goToChildView.delegate = self  // don't forget to add this line
self.navigationController?.pushViewController(goToChildView, animated: true)
 

 

 

To pass data from ChildViewController to ParentViewController :

 

You can pass data back using delegate. Follow the following steps to pass the data from ChildViewController to ParentViewController :

1) Create protocol in ChildViewController

2) Create delegate variable in ChildViewController

3) Extend ChildViewController protocol in ParentViewController

4) Give reference to ChildViewController of ParentViewController when navigate

5) Define delegate Method in ParentViewController

6) Then you can call delegate method from ChildViewController

 

In ChildViewController :

protocol ChildViewControllerDelegate { 
    func childViewControllerResponse(parameter) 
} 
class ChildViewController:UIViewController { 
    var delegate: ChildViewControllerDelegate? .... 
}
 

 

In ParentViewController :

// extend `delegate` 
class ParentViewController:UIViewController,ChildViewControllerDelegate { 
    // Define Delegate Method 
    func childViewControllerResponse(parameter) { 
        .... // self.parameter = parameter 
    } 
}
 

 

Method Calling :

self.delegate?.childViewControllerResponse(parameter)
 

 

This is all you need to do.

Thanks for reading this blog!

 

About Author

Author Image
Akshay Luthra

Akshay Luthra has excellent experience in developing Cross Platform Mobile Apps using JavaScript and Titanium Framework. He loves listening to music and travelling new places.

Request for Proposal

Name is required

Comment is required

Sending message..