Implemention of custom delegates in swift.

Updated 2 March 2021

Save

What are delegates?

Delegates are a design pattern that allows one object to send messages to another object when a specific event happens. Delegation is a simple and powerful pattern in which one object in a program acts on behalf of, or in coordination with, another object.

Suppose that, 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 the necessary action, this can be carried out with the help of delegates!

We will understand the whole delegation process through an example. Then, it will easy to understand.

So, Here we go.

Step 1: Take two view controllers that is FirstViewController and SecondViewContoller. In this example, we write data in the text field of the second view controller and pass data back to the first view controller. Which will reflect in the label.

.            

 

Step 2: Make a class for the second view controller. In the below code you can see we declared a protocol name “PassData”. In which we declare one function. We only declare the function not defining it. We define the function at the time of calling the protocol. Make one variable of the protocol. And call the protocol function when we click the send button.

Step 3: Make a class of First View controller. Here is the code. In this code, you can see we inherit the protocol over there. Then we call and define the function of the protocol. In this function, we are fetching the data from the second view controller which will reflect data into the first view controller. We make delegates for passing data from one view controller to another.

Output: –  In the result, you can see we type “hello there??” in the text field of the second view controller and it will reflect on the first view controller.

So finally we learn how to make custom delegates. Delegates are an important design pattern to understand. you can see more about protocols here.

Conclusion: –

Thank you.Hope you like it. I hope that will help you to understand protocol delegates.

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home