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.