Swift delegate design sample – The.Swift.Dev.


Implementing delegation in Swift

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

See? That is delegation. In some unspecified time in the future an occasion occurred, so the delegator (supervisor) utilized an exterior useful resource (a developer) utilizing a standard interface (challenge describing the issue for each social gathering) to do obtain one thing (repair the 🐛).

To reveal how delegation works in actual life I made a fairly easy instance. I will use an analogous method (as a result of Xcode playgrounds are nonetheless freezing each 1-5 minutes) like I did for the command sample, however the objective of this one goes to be virtually solely 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 go away simply inform me "bye":")
    }

    func didReceive(enter: String) {
        swap enter {
        case "hello":
            print("🌎 Whats up 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 individual delegate sample in Swift. You possibly can think about that Apple is doing the identical factor below the hood, with UICollectionViewDataSource, UICollectionViewDelegate and many others. You solely should implement the delegate, they will present the protocol and the delegator. 🤔

Weak properties, delegates and courses

Reminiscence administration is an important factor so it is value to say that each one the category delegates needs to be weak properties, otherwise you’ll create a extremely 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’ll be able to see delegation is fairly simple, however it may be harmful. It helps decoupling by offering a standard interface that can be utilized by anybody who implements the delegate (typically knowledge supply) protocol. There are actually wonderful articles about delegates, if you would like to know extra about this sample, you need to examine them out.

Recent Articles

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here

Stay on op - Ge the daily news in your inbox