Created
November 22, 2024 08:08
Plug-in architecture
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Plugin type alias | |
typealias Plugin<T> = (T) -> T | |
// Plugin protocol for flexibility | |
protocol Pluginable { | |
associatedtype T | |
var plugins: [Plugin<T>] { get set } | |
func applyPlugins(to value: T) -> T | |
} | |
extension Pluginable { | |
func applyPlugins(to value: T) -> T { | |
return plugins.reduce(value) { value, plugin in | |
plugin(value) | |
} | |
} | |
} | |
// Example ViewModel | |
struct FirstViewModel { | |
var title: String | |
} | |
// Example ViewController | |
class FirstVC: UIViewController, Pluginable { | |
var viewModel: FirstViewModel | |
var plugins: [Plugin<FirstViewModel>] = [] | |
required init(viewModel: FirstViewModel) { | |
self.viewModel = viewModel | |
super.init(nibName: nil, bundle: nil) | |
} | |
required init?(coder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
let updatedViewModel = applyPlugins(to: viewModel) | |
// Update the UI based on the modified viewModel | |
} | |
} | |
// Example Plugin | |
let capitalizeTitlePlugin: Plugin<FirstViewModel> = { viewModel in | |
var newViewModel = viewModel | |
newViewModel.title = newViewModel.title.uppercased() | |
return newViewModel | |
} | |
let prefixTitlePlugin: Plugin<FirstViewModel> = { viewModel in | |
var newViewModel = viewModel | |
newViewModel.title = "Prefix: " + newViewModel.title | |
return newViewModel | |
} | |
// Create an instance of FirstVC with plugins | |
let viewModel = FirstViewModel(title: "hello") | |
var firstVC = FirstVC(viewModel: viewModel) | |
firstVC.plugins = [capitalizeTitlePlugin, prefixTitlePlugin] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment