Friday, March 24, 2023
Learning Code
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
Learning Code
No Result
View All Result
Home Swift

Modules and hooks in Swift

learningcode_x1mckf by learningcode_x1mckf
September 23, 2022
in Swift
0
Modules and hooks in Swift
74
SHARES
1.2k
VIEWS
Share on FacebookShare on Twitter


You might also like

Encoding and decoding data using the Hummingbird framework

Hummingbird routing and requests – The.Swift.Dev.

Building a Scrollable Custom Tab Bar in SwiftUI

How do modules (plugins) work?

Would not be cool in case you may create objects that would work collectively with out realizing about one another? Think about that you’re constructing a dynamic kind. Primarily based on some inner circumstances, the fields are going to be composed utilizing the info coming from the enabled modules.

For instance you have got module A, B, C, the place A is offering you Area 1, 2, 3, the B module is taking good care of Area 4, 5 and C is the supplier of Area 6. Now in case you flip off B, it is best to solely have the ability to see area 1, 2, 3 and 6. If every little thing is turned on it is best to see all of the fields from 1 to six.

We will apply this very same sample to many issues. Simply take into consideration one of many largest plugin ecosystem. WordPress is utilizing hooks to increase the core functinalities via them. It is all primarily based on the idea I simply talked about above. That is a part of the event-driven architecture design sample. Now the query is how can we implement one thing comparable utilizing Swift? πŸ€”

A hook system implementation

First we begin with a protocol with a degree of invocation. This methodology will likely be known as by the module supervisor to invoke the right hook perform by title. We’ll cross round a dictionary of parameters, so our hooks can have arguments. We’re utilizing the Any sort right here as a price, so you’ll be able to ship something as a parameter beneath a given key.

protocol Module 
    func invoke(title: String, params: [String: Any]) -> Any?


extension Module 
    func invoke(title: String, params: [String: Any]) -> Any?  nil 

Now let’s implement our modules utilizing a simplified model primarily based on the shape instance. πŸ€“

class A: Module 

    func invoke(title: String, params: [String: Any]) -> Any? 
        swap title 
        case "example_form":
            return self.exampleFormHook()
        default:
            return nil
        
    

    non-public func exampleFormHook() -> [String] 
        ["Field 1", "Field 2", "Field 3"]
    


class B: Module 
    func invoke(title: String, params: [String: Any]) -> Any? 
        swap title 
        case "example_form":
            return self.exampleFormHook()
        default:
            return nil
        
    

    non-public func exampleFormHook() -> [String] 
        ["Field 4", "Field 5"]
    


class C: Module 
    func invoke(title: String, params: [String: Any]) -> Any? 
        swap title 
        case "example_form":
            return self.exampleFormHook()
        default:
            return nil
        
    

    non-public func exampleFormHook() -> [String] 
        ["Field 6"]
    

Subsequent we want a module supervisor that may be initialized with an array of modules. This supervisor will likely be answerable for calling the appropriate invocation methodology on each single module and it will deal with the returned response in a type-safe method. We’ll implement two invoke methodology variations instantly. One for merging the outcome and the opposite to return the primary results of a hook.

You’ll be able to attempt to implement a model that may merge Bool values utilizing the && operator

Right here is our module supervisor implementation with the 2 generic strategies:

struct ModuleManager 

    let  modules: [Module]
    
    func invokeAllHooks<T>(_ title: String, sort: T.Sort, params: [String: Any] = [:]) -> [T] 
        let outcome = self.modules.map  module in
            module.invoke(title: title, params: params)
        
        return outcome.compactMap  $0 as? [T] .flatMap  $0 
    

    func invokeHook<T>(_ title: String, sort: T.Sort, params: [String: Any] = [:]) -> T? 
        for module in self.modules 
            let outcome = module.invoke(title: title, params: params)
            if outcome != nil 
                return outcome as? T
            
        
        return nil
    

You need to use the the invokeAllHooks methodology to merge collectively an array of a generic sort. That is the one which we are able to use to collect all he kind fields utilizing the underlying hook strategies.

let manager1 = ModuleManager(modules: [A(), B(), C()])
let form1 = manager1.invokeAllHooks("example_form", sort: String.self)
print(form1) 

let manager2 = ModuleManager(modules: [A(), C()])
let form2 = manager2.invokeAllHooks("example_form", sort: String.self)
print(form2) 

Utilizing the invokeHook methodology you’ll be able to obtain the same conduct just like the chain of accountability design sample. The responder chain works very comparable similiar, Apple makes use of responders on nearly each platform to deal with UI occasions. Let me present you the way it works by updating module B. 🐝

class B: Module 
    func invoke(title: String, params: [String: Any]) -> Any? 
        swap title 
        case "example_form":
            return self.exampleFormHook()
        case "example_responder":
            return self.exampleResponderHook()
        default:
            return nil
        
    

    non-public func exampleFormHook() -> [String] 
        ["Field 4", "Field 5"]
    
    
    non-public func exampleResponderHook() -> String 
        "Hey, that is module B."
    

If we set off the brand new example_responder hook with the invokeHook methodology on each managers we’ll see that the result is kind of totally different.

if let worth = manager1.invokeHook("example_responder", sort: String.self) 
    print(worth) 


if let worth = manager2.invokeHook("example_responder", sort: String.self) 
    print(worth) 

Within the first case, since we now have an implementation in one among our modules for this hook, the return worth will likely be current, so we are able to print it. Within the second case there isn’t a module to deal with the occasion, so the block contained in the situation will not be executed. Instructed ya’, it is like a responder chain. 😜



Source link

Share30Tweet19
learningcode_x1mckf

learningcode_x1mckf

Recommended For You

Encoding and decoding data using the Hummingbird framework

by learningcode_x1mckf
March 22, 2023
0
Encoding and decoding data using the Hummingbird framework

HTTP is all about sending and receiving information over the community. Initially it was solely utilized to switch HTML paperwork, however these days we use HTTP to switch...

Read more

Hummingbird routing and requests – The.Swift.Dev.

by learningcode_x1mckf
March 17, 2023
0
Hummingbird routing and requests – The.Swift.Dev.

Routing on the server facet means the server goes to ship a response primarily based on the URL path that the consumer referred to as when firing up...

Read more

Building a Scrollable Custom Tab Bar in SwiftUI

by learningcode_x1mckf
March 10, 2023
0
Building a Scrollable Custom Tab Bar in SwiftUI

Whether or not you’re making a social media app or a productiveness device, the tab bar interface can improve the consumer expertise by making it extra intuitive and...

Read more

Beginner’s guide to server-side Swift using the Hummingbird framework

by learningcode_x1mckf
March 8, 2023
0
Beginner’s guide to server-side Swift using the Hummingbird framework

Swift on the Server in 2023 Three years in the past I began to focus on Vapor, the preferred web-framework written in Swift, which served me very...

Read more

What’s new in Swift 5.8 – Hacking with Swift

by learningcode_x1mckf
March 8, 2023
0
What’s new in Swift 5.8 – Hacking with Swift

Though many main Swift modifications are at present percolating by way of Swift Evolution, Swift 5.8 itself is extra of a clear up launch: there are additions, sure,...

Read more
Next Post
Meet Bun: A JavaScript Runtime for the Whole Dev Lifecycle

Meet Bun: A JavaScript Runtime for the Whole Dev Lifecycle

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Related News

Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

How to Use ESLint With the Airbnb JavaScript Style Guide – MUO – MakeUseOf

February 10, 2023
Display Desktop Notifications Using JavaScript

Display Desktop Notifications Using JavaScript

October 30, 2022
Reminder: Java and Jazz is Tonight in Jefferson | Raccoon Valley Radio

Reminder: Java and Jazz is Tonight in Jefferson | Raccoon Valley Radio

November 12, 2022

Browse by Category

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

RECENT POSTS

  • Java Developer Survey Reveals Increased Need for Java … – PR Newswire
  • What You Should Definitely Pay Attention to When Hiring Java Developers – Modern Diplomacy
  • Java Web Frameworks Software Market Research Report 2023 … – Los Alamos Monitor

CATEGORIES

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

Β© 2022 Copyright Learning Code

No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#

Β© 2022 Copyright Learning Code

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?