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:

delegate?.launchObjectSuccess()

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s