Different ways to pass data between viewcontrollers/views
You can pass data between viewcontroller in different way in swift. In this article we’re going to explore the different ways to pass data.
To know more about the code and flow please download the sample project from GitHub here
- using property
- using functions.
- using init method
- using segues
- using closures
- using delegates
- using NotificationCenter
- using Singleton
Passing Data by using property or function:
Property is a variable that is part of class. You can pass the data using function or using parameter. Each instance of class will have that function and property. you can assign the value by passing data as argument into the function or you can assign a value to property.
Passing data in init method:
you can pass data to the class using init method as follows
Passing data using segues:
If you’re using Storyboards, you can pass data between view controllers with segues, using the prepare(for:sender:)
function.
- You need to create a segue between viewcontrollers in storyboard
- Assign an identifier name to segue.
- use
prepare(for:sender:)
method to pass the function.
Two way you can create segue between viewcontrollers.
- Control + click the UI element you are going to use to make the bridge and drag to the second View Controller and then add the identifier to the segue.
2. Control + click the viewcontroller you are going to use to make the bridge and drag to the second View Controller and then add the identifier to the segue.
- after adding segue, add UIButton/UIControl subclass programatically or through storyboard
- add Target/IBAction to the UIButton/UIControl.
- then use performSegue(withIdentifier: “”, sender: ) in Target/IBAction to create the bridge between two view controllers.
- After creating segue using any one of the way, override the
prepare(for segue: UIStoryboardSegue, sender: Any?)
method to pass data.
Passing data with closures:
Closures are blocks of code that can be passed around in your code to share data between View Controllers. Using trailing closure you can share data between the viewcontroller.
e.g: func callApi(_ msg: String, completion: (String)->Void)
In above example, we can pass data between two viewcontroller using completion block.
To know more about closure please check out my blog for closures here.
Passing data with delegates:
Delegate is a design pattern used to exchange data between objects. It allows object to communicate back to its owner. Delegates are mainly used during 1–1 communication between object.
Passing data by using Singleton object:
Singleton guarantees that your app contains only one instance of the object and can be accessed anywhere in the app.
Passing data by using Notification Center:
Notification center is the observer design pattern
. notification center establishes 1-many communication between object.