Swift delegate design sample – The.Swift.Dev.



· 1 min learn


The delegate design sample is a comparatively straightforward strategy to talk between two objects by way of a typical interface, protocol in Swift.

Implementing delegation in Swift

You’ll want a delegate protocol, a delegator who really delegates out the duties and a delegate object that implements the delegate protocol and does the precise work that was requested by the “boss”. Let’s translate this into human.

The consumer experiences a bug. The challenge supervisor creates a difficulty and tells one of many builders to repair the issue asap.

See? That’s delegation. Sooner or later an occasion occurred, so the delegator (supervisor) utilized an exterior useful resource (a developer) utilizing a typical interface (subject describing the issue for each celebration) to do obtain one thing (repair the 🐛).

To exhibit how delegation works in actual life I made a reasonably easy instance. I’m going to make use of the same method (as a result of Xcode playgrounds are nonetheless freezing each 1-5 minutes) like I did for the command sample, however the function of this one goes to be virtually completely totally different, as a result of we’re speaking about delegation. 😅

#!/usr/bin/env swift

import Basis


protocol InputDelegate {

    var shouldContinueListening: Bool { get }

    func didStartListening()
    func didReceive(enter: String)
}


class InputHandler {

    var delegate: InputDelegate?

    func pay attention() {
        self.delegate?.didStartListening()

        repeat {
            guard let enter = readLine() else {
                proceed
            }
            self.delegate?.didReceive(enter: enter)
        }
        whereas self.delegate?.shouldContinueListening ?? false
    }
}


struct InputReceiver: InputDelegate {

    var shouldContinueListening: Bool {
        return true
    }

    func didStartListening() {
        print("👻 Please be good and say "hello", if you wish to depart simply inform me "bye":")
    }

    func didReceive(enter: String) {
        change enter {
        case "hello":
            print("🌎 Howdy world!")
        case "bye":
            print("👋 Bye!")
            exit(0)
        default:
            print("🔍 Command not discovered! Please strive once more:")
        }
    }
}

let inputHandler = InputHandler()
let inputReceiver = InputReceiver()
inputHandler.delegate = inputReceiver
inputHandler.pay attention()

That is how one can create your personal delegate sample in Swift. You possibly can think about that Apple is doing the identical factor underneath the hood, with UICollectionViewDataSource, UICollectionViewDelegate and many others. You solely should implement the delegate, they’ll present the protocol and the delegator. 🤔

Weak properties, delegates and courses

Reminiscence administration is a vital factor so it’s value to say that every one the category delegates needs to be weak properties, otherwise you’ll create a very dangerous retain cycle. 😱

protocol InputDelegate: class { /*...*/ }

class InputHandler {

    weak var delegate: InputDelegate?

    /*...*/
}

class InputReceiver: InputDelegate {
    /*...*/
}

Right here is the altered Swift code snippet, however now utilizing a category because the delegate. You simply have to vary your protocol just a little bit and the property contained in the delegator. All the time use weak delegate variables if you’re going to assign a category as a delegate. ⚠️

As you possibly can see delegation is fairly straightforward, however it may be harmful. It helps decoupling by offering a typical interface that can be utilized by anybody who implements the delegate (typically information supply) protocol. There are actually wonderful articles about delegates, when you’d prefer to know extra about this sample, it’s best to verify them out.

Associated posts


On this article I’m going to point out you learn how to implement a primary occasion processing system to your modular Swift software.


Be taught the iterator design sample by utilizing some customized sequences, conforming to the IteratorProtocol from the Swift customary library.


Discover ways to use lazy properties in Swift to enhance efficiency, keep away from optionals or simply to make the init course of extra clear.


Newbie’s information about optics in Swift. Discover ways to use lenses and prisms to control objects utilizing a practical method.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles