Occasion-driven generic hooks for Swift


Dependencies, protocols and kinds

Once we write Swift, we are able to import frameworks and different third occasion libraries. It is fairly pure, simply take into consideration Basis, UIKit or these days it is extra probably SwiftUI, however there are lots of different dependencies that we are able to use. Even once we do not import something we normally create separate constructions or courses to construct smaller elements as a substitute of 1 gigantic spaghetti-like file, operate or no matter. Think about the next instance:

struct NameProvider {
    func getName() -> String { "John Doe" }
}


struct App {
    let supplier = NameProvider()
    
    func run() {
        let title = supplier.getName()
        print("Howdy (title)!")
    }
}

let app = App()
app.run()

It exhibits us the fundamentals of the separation of issues precept. The App struct the illustration of our primary software, which is an easy “Howdy World!” app, with a twist. The title will not be hardcoded into the App object, however it’s coming from a NameProvider struct.

The factor that it is best to discover is that we have created a static dependency between the App and the NameProvider object right here. We do not have to import a framework to create a dependency, these objects are in the identical namespace, however nonetheless the appliance will all the time require the NameProvider kind at compilation time. This isn’t unhealthy, however generally it isn’t what we actually need.

How can we remedy this? Wait I’ve an concept, let’s create a protocol! 😃

import Basis

struct MyNameProvider: NameProvider {
    func getName() -> String { "John Doe" }
}


protocol NameProvider {
    func getName() -> String
}

struct App {
    let supplier: NameProvider
    
    func run() {
        let title = supplier.getName()
        print("Howdy (title)!")
    }
}

let supplier = MyNameProvider()
let app = App(supplier: supplier)
app.run()

Oh no, this simply made our total codebase a bit tougher to know, additionally did not actually solved something, as a result of we nonetheless cannot compile our software with out the MyNameProvider dependency. That class have to be a part of the bundle regardless of what number of protocols we create. In fact we may transfer the NameProvider protocol right into a standalone Swift bundle, then we may create one other bundle for the protocol implementation that depends on that one, then use each as a dependency once we construct our software, however hey is not this getting slightly bit sophisticated? 🤔

What did we acquire right here? Initially we overcomplicated a extremely easy factor. Alternatively, we eradicated an precise dependency from the App struct itself. That is an awesome factor, as a result of now we may create a mock title supplier and check our software occasion with that, we are able to inject any sort of Swift object into the app that conforms to the NameProvider protocol.


Can we modify the supplier at runtime? Nicely, sure, that is additionally potential we may outline the supplier as a variable and alter its worth in a while, however there’s one factor that we won’t remedy with this method. We won’t transfer out the supplier reference from the appliance itself. 😳

Occasion-driven structure

The EDA design sample permits us to create loosely coupled software program elements and providers with out forming an precise dependency between the individuals. Think about the next various:

struct MyNameProvider {
    func getName(_: HookArguments) -> String { "John Doe" }
}

struct App {

    func run() {
        guard let title: String = hooks.invoke("name-event") else {
            fatalError("Somebody should present a name-event handler.")
        }
        print("Howdy (title)!")
    }
}

let hooks = HookStorage()

let supplier = MyNameProvider()
hooks.register("name-event", use: supplier.getName)

let app = App()
app.run()

Do not attempt to compile this but, there are some extra issues that we’ll must implement, however first I’m going to elucidate this snippet step-by-step. The MyNameProvider struct getName operate signature modified a bit, as a result of in an event-driven world we want a unified operate signature to deal with all sort of situations. Fortuitously we do not have to erease the return kind to Any because of the wonderful generic assist in Swift. This HookArguments kind will likely be simply an alias for a dictionary that has String keys and it may well have Any worth.

Now contained in the App struct we call-out for the hook system and invoke an occasion with the “name-event” title. The invoke technique is a operate with a generic return kind, it really returns an optionally available generic worth, therefore the guard assertion with the specific String kind. Lengthy story brief, we name one thing that may return us a String worth, in different phrases we fireplace the title occasion. 🔥

The final half is the setup, first we have to initialize our hook system that may retailer all of the references for the occasion handlers. Subsequent we create a supplier and register our handler for the given occasion, lastly we make the app and run the whole lot.

I am not saying that this method is simpler than the protocol oriented model, however it’s very completely different for positive. Sadly we nonetheless must construct our occasion handler system, so let’s get began.

public typealias HookArguments = [String: Any]


public protocol HookFunction {
    func invoke(_: HookArguments) -> Any
}


public typealias HookFunctionSignature<T> = (HookArguments) -> T

As I discussed this earlier than, the HookArguments is only a typealias for the [String:Any] kind, this fashion we’re going to have the ability to move round any sort of values below given keys for the hook features. Subsequent we outline a protocol for invoking these features, and eventually we construct up a operate signature for our hooks, that is going for use in the course of the registration course of. 🤓

public struct AnonymousHookFunction: HookFunction {

    personal let functionBlock: HookFunctionSignature<Any>

    
    public init(_ functionBlock: @escaping HookFunctionSignature<Any>) {
        self.functionBlock = functionBlock
    }

    
    public func invoke(_ args: HookArguments) -> Any {
        functionBlock(args)
    }
}

The AnonymousHookFunction is a helper that we are able to use to move round blocks as a substitute of object pointers once we register a brand new hook operate. It may be fairly useful generally to write down an occasion handler with out creating extra courses or structs. We’re going to additionally must affiliate these hook operate pointers with an occasion title and an precise a return kind…

public last class HookFunctionPointer {

    public var title: String
    public var pointer: HookFunction
    public var returnType: Any.Sort
    
    public init(title: String, operate: HookFunction, returnType: Any.Sort) {
        self.title = title
        self.pointer = operate
        self.returnType = returnType
    }
}

The HookFunctionPointer is used contained in the hook storage, that is the core constructing block for this whole system. The hook storage is the place the place all of your occasion handlers stay and you’ll name these occasions by means of this storage pointer when you could set off an occasion. 🔫

public last class HookStorage {
    
    personal var pointers: [HookFunctionPointer]

    public init() {
        self.pointers = []
    }

    public func register<ReturnType>(_ title: String, use block: @escaping HookFunctionSignature<ReturnType>) {
        let operate = AnonymousHookFunction { args -> Any in
            block(args)
        }
        let pointer = HookFunctionPointer(title: title, operate: operate, returnType: ReturnType.self)
        pointers.append(pointer)
    }

    
    public func invoke<ReturnType>(_ title: String, args: HookArguments = [:]) -> ReturnType? {
        pointers.first { $0.title == title && $0.returnType == ReturnType.self }?.pointer.invoke(args) as? ReturnType
    }

    
    public func invokeAll<ReturnType>(_ title: String, args: HookArguments = [:]) -> [ReturnType] {
        pointers.filter { $0.title == title && $0.returnType == ReturnType.self }.compactMap { $0.pointer.invoke(args) as? ReturnType }
    }
}

I do know, this looks like fairly sophisticated at first sight, however if you begin enjoying round with these strategies it’s going to all make sense. I am nonetheless undecided concerning the naming conventions, for instance the HookStorage can also be a world occasion storage so possibly it would be higher to name it one thing associated to the occasion time period. When you have a greater concept, be happy to tweet me.

Oh, I nearly forgot that I needed to point out you how you can register an nameless hook operate. 😅

hooks.register("name-event") { _ in "John Doe" }

That is it you do not occasion have to write down the return kind, the Swift compiler this time is wise sufficient to determine the ultimate operate signature. This magic solely works with one-liners I suppose… ✨

This text was a follow-up on the modules and hooks in Swift, additionally closely innspired by the my previous Entropy framework, Drupal and the WordPress hook methods. The code implementation concept comes from the Vapor’s routing abstraction, however it’s barely modified to match my wants.

The event-driven design method is a really good structure and I actually hope that we’ll see the long run good thing about utilizing this sample inside Feather. I can not wait to let you know extra about it… 🪶



Leave a Reply