Swift delegation

Swift Delegation

There are times when you have Class objects that you need to communicate back to some part of your application. With delegation, it’s a 1-to-1 relationship. Generally where the object(s) are instantiated is where you’d like to gain insight upon an event or events.

Notifications can handle 1-to-n types of relationships. That’s not what we’re doing here.

So, for this example, we have a Class object we’ll call blob. After it’s created, we want to know when a button within the object is selected. It’s within the object itself, so it’s out of scope in our ViewController. There is where delegation comes into play. Here is the class object in question.

protocol BlobDelegate {
    func blobPressed(index: Int)

import UIKit

class Blob: UIView {

    var delegate: BlobDelegate?
    var button: UIButton!
    override init(frame: CGRect) {
        button = UIButton(frame: frame)
        button.backgroundColor = UIColor.red.withAlphaComponent(0.2)
        button.addTarget(self, action: #selector(clicked), for: .touchUpInside)
    @objc func clicked() {
        delegate?.blobPressed(index: 2)
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")

The top bit of code is the protocol – which is our delegate. When our button is pressed, it calls the function in the delegate – and passes an Int as the argument. For now it’s just a simple hard-coded number to show it working.

All one need to do now is to assign the delegate when creating the Class object from outside the class (instantiation) while conforming to the protocol.

import UIKit

class ViewController: UIViewController, BlogDelegate
    var blob: Blob!
    override func viewDidLoad()
        blob = Blob(frame: CGRect(x:0, y:0, width: 100; height: 100))
        blob.delegate = self

    // Method from the delegate.
    func blobPressed(index: Int) {
        print("From blob: \(index)")

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.