How to Create Delegates in Swift

What are delegates?

Delegates are the objects which allow one object to send a message as events happen. Imagine an object A calls an object B to perform an action. Once the action is complete, object A should know that B has completed the task and take necessary action, this can be achieved with the help of delegates!

Delegate == Protocol

Creating a delegate is as simple as creating a protocol — that’s pretty all it is.

protocol CastHandlerDelegate: class {

    /// Media Launched successfully on the cast device
    func launchObjectSuccess()


Calling the delegate

To use the delegate we add an optional variable to the class we’ll be sending notifications from.

weak var delegate: CastHandlerDelegate?

We can then call this from anywhere within that class like so:


Conforming to CastHandlerDelegate

As you probably already know, the next step is to conform to the delegate. First, we tell the class it needs to implement the methods set in the delegate.

class AViewController: UIViewController, CastHandlerDelegate {


Next, we implement the methods within our delegate.

class AViewController: UIViewController, CastHandlerDelegate {

    func launchObjectSuccess() {
        print("Media successfully launched!")


That’s it! Our delegate has been created and we’re successfully calling the method.


How to pass data back to previous ViewController using PresentViewController

Let suppose, We have to pass data from B to A ViewController. Here, I am using Present View Controller. When you  dismiss PresentViewController, Data will back to Parent View Controller.

In the B viewController.h File,

@protocol senddata <NSObject>
-(void) Passdatatoback:(NSString*)Passdataback;

Also set the property in .h file,

@property(nonatomic, assign)id delegate;

Now, move to B viewController.m File,

@synthesize delegate;

and set a method,

[delegate Passdatatoback:@”This is data which you want in A ViewController”];

Now, Move to A viewController,

Create a same method which you have create in B ViewController.m file.

-(void) Passdatatoback:(NSString*)Passdataback{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Your string Data Showing” message:Passdataback delegate:self cancelButtonTitle:@”OK “ otherButtonTitles:nil];
 [alert show];

In A ViewContrller.m file, When You go in B ViewController,

BViewConoller *BVC = [[BViewConoller alloc]init];
BVC.delegate= self;
[self.navigationController presentViewController:BVC animated:YES completion:nil];

That’s It.

If you like this post, Please comment below or subscribe this blog.

Leave your comments