11.2 C
Canberra
Saturday, October 25, 2025

Swift delegate design sample – The.Swift.Dev.



· 1 min learn


The delegate design sample is a comparatively simple option to talk between two objects by a typical interface, protocol in Swift.

Implementing delegation in Swift

You’ll want a delegate protocol, a delegator who truly 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 reviews a bug. The undertaking supervisor creates a problem 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 (concern describing the issue for each occasion) to do obtain one thing (repair the 🐛).

To display how delegation works in actual life I made a fairly easy instance. I’m going to make use of an identical method (as a result of Xcode playgrounds are nonetheless freezing each 1-5 minutes) like I did for the command sample, however the goal of this one goes to be virtually totally 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 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 depart 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 strive 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’ll be able to think about that Apple is doing the identical factor beneath the hood, with UICollectionViewDataSource, UICollectionViewDelegate and so on. You solely must implement the delegate, they’ll present the protocol and the delegator. 🤔

Weak properties, delegates and lessons

Reminiscence administration is a vital factor so it’s price to say that every one the category delegates must be weak properties, otherwise you’ll create a very unhealthy 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 somewhat bit and the property contained in the delegator. At all times use weak delegate variables if you’re going to 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 (typically information supply) protocol. There are actually superb articles about delegates, if you happen to’d prefer to know extra about this sample, you must examine them out.

Associated posts


On this article I’m going to indicate you the right way to implement a primary occasion processing system in your modular Swift software.


Be taught the iterator design sample through the use of 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 govern objects utilizing a purposeful method.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

[td_block_social_counter facebook="tagdiv" twitter="tagdivofficial" youtube="tagdiv" style="style8 td-social-boxed td-social-font-icons" tdc_css="eyJhbGwiOnsibWFyZ2luLWJvdHRvbSI6IjM4IiwiZGlzcGxheSI6IiJ9LCJwb3J0cmFpdCI6eyJtYXJnaW4tYm90dG9tIjoiMzAiLCJkaXNwbGF5IjoiIn0sInBvcnRyYWl0X21heF93aWR0aCI6MTAxOCwicG9ydHJhaXRfbWluX3dpZHRoIjo3Njh9" custom_title="Stay Connected" block_template_id="td_block_template_8" f_header_font_family="712" f_header_font_transform="uppercase" f_header_font_weight="500" f_header_font_size="17" border_color="#dd3333"]
- Advertisement -spot_img

Latest Articles