Friday, November 6, 2026
HomeiOS DevelopmentSwift delegate design sample - The.Swift.Dev.

Swift delegate design sample – The.Swift.Dev.

[ad_1]

Implementing delegation in Swift

You will 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 shopper studies a bug. The undertaking supervisor creates a problem and tells one of many builders to repair the issue asap.

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

To exhibit how delegation works in actual life I made a fairly easy instance. I will use an analogous strategy (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 nearly totally completely 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 hear() {
        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 go away simply inform me "bye":")
    }

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

let inputHandler = InputHandler()
let inputReceiver = InputReceiver()
inputHandler.delegate = inputReceiver
inputHandler.hear()

That is how one can create your personal delegate sample in Swift. You may think about that Apple is doing the identical factor below the hood, with UICollectionViewDataSource, UICollectionViewDelegate and so on. You solely must implement the delegate, they will present the protocol and the delegator. 🤔

Weak properties, delegates and lessons

Reminiscence administration is an important factor so it is price to say that each one the category delegates must be weak properies, otherwise you’ll create a very dangerous reatin 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 alter your protocol somewhat bit and the property contained in the delegator. All the time use weak delegate variables if you’ll assign a category as a delegate. ⚠️

As you possibly can see delegation is fairly simple, however it may be harmful. It helps decoupling by offering a typical interface that can be utilized by anybody who implements the delegate (generally information supply) protocol. There are actually superb articles about delegates, if you would like to know extra about this sample, you need to verify them out.

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments