Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between a Callback and Competition Handler in Swift

Tags:

swift

In the Combine framework, I have found following text

The Combine framework provides a declarative approach for how your app processes events. Rather than potentially implementing multiple delegate callbacks or completion handler

Can somebody tell me what is the difference between completion handler and callback in Swift?

like image 743
Blazej SLEBODA Avatar asked Oct 20 '25 16:10

Blazej SLEBODA


2 Answers

A delegate callback is when you have a delegate that you know in advance implements a method (e.g. because it adopts a protocol), and you call that method by name.

A completion handler is when someone hands you a function and you just call it blindly by reference.

like image 165
matt Avatar answered Oct 23 '25 07:10

matt


Callback is a way to sending data back to some other function on some particular occasion. there are 2 ways to implement callbacks in swift.

  1. Using Protocols / Delegate
  2. Using Completion Handler

Using Protocols / Delegate Example:

Declare Protocol

protocol MyDelegate {
     public method(param: String);
}

Your ViewController should extend the delegate

class YourViewController: MyDelegate {
     // Your Other methods

     func method(param: String) {
      // Do your stuff
     }
 }

Now in your other classes you can send callback to ViewController through delegate object like

delegate.method(param: "your_param");

Using Completion Handler Example:

public func method(param: String, completionHandler: @escaping (_ param: String) -> Void)
{
    ...
    // now you can send data back to the caller function using completionHandler on some particular occasion 
     completionHandler("param");
}

We can call this function like

method(param: String, completionHandler: { (result, alreadyUserId) in
      // here you will receive callback
});
like image 28
Asad Ali Choudhry Avatar answered Oct 23 '25 07:10

Asad Ali Choudhry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!