Updated 26 December 2023
Hi folks, today we will learn another interesting topic with mobikul blogs on Nested Callback in Swift.
In Swift programming, a nested callback is a situation where a function or closure (callback) is defined within the scope of another closure and is continuously being passed as an argument for the execution of another operation.
You can check the nested callback structure below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
func multiply(_ a: Int, _ b: Int, completion: @escaping(Int?) -> Void){ completion(a * b) } multiply(2, 3) { result in multiply (result, 4) { result2 in multiply (result2, 5) { result3 in print(result3) } } } // OutPut* 120 |
Before learning nested callback handling, it is a prerequisite to know about the callback handling in Swift.
In Swift, Nested callbacks are often used for asynchronous operations like Network Request, Data Processing etc..
Now suppose you hit a request to the network manager using callback and get the request result back in the ViewModel and want back data again into UIViewController.
Usually, we use NotificationCenter or Delegates to inform the controller that data is stored in the object after that we reload table view, collection view or draw view to represent data on the screen. But, there is a better way to complete the operation by using callbacks.
Example of creating nested callbacks for asynchronous operations:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
typealias ServiceResponse = (ResponseModel?, Error?) -> Void class NetworkManager : NSObject { func fetchData (params : String, _completion: @escaping ServiceResponse ) -> Void { // Perform some async operation like api calling self.doFurtherProcessing(data: apiResponse) {(result: ResponseModel?, error : Error ?) in _completion(result, error as NSError) } } func doFurtherProcessing(data: JSON?, taskCallback: @escaping (ResponseModel?, Error?) -> Void) { // Perform operation like data parsing or logics and return the data with callback ResponseModel model = ParsigJsonResponse(data) taskCallback(model, error as NSError) } } |
For accessing the asynchronous operation response on your ViewController or ViewModel. You will need to place the below code on the same.
1 2 3 4 5 6 7 8 9 |
class ViewModel : NSObject { func callingData(){ let networkManager = NetworkManager() networkManager.fetchData (params: params) { (asyncResponse: JSON?, error : Error ?) in print(asyncResponse) self.tableView.reloadData() } } } |
So, In this article, we have learned about the Nested Callbacks in Swift and how can we handle these callbacks on our code effectively.
You can also learn more about Swift with Mobikul Blogs.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.