Hi Swift experts!
I'm looking for some help on how to implement this properly.
I have a protocol for a Command with a strong typed parameter:
protocol Command {
associatedtype Parameter
func canExecute(for: Parameter) -> Bool
func execute(with: Parameter) async
}
and I have a protocol for a Command Manager:
protocol CommandManaging {
associatedtype C where C: Command
var managedCommands: [C] { get }
func updateCommands(parameter: C.Parameter)
}
I'd like to implement Command Manager but keep the Parameter generic
class CommandManager<Parameter>: CommandManaging {
// How to implement this?
}
so that other components can use it like this:
let manager: CommandManager<Int> = .init([command1, command2])
manager.updateCommands(parameter: 123)
But I can't find the proper way to implement the CommandManager class.
Is his even possible?
Hi, try this code:
struct CommandInt: Command {
func canExecute(for value: Int) -> Bool { true }
func execute(with value: Int) async { }
}
class CommandManager<T: Command>: CommandManaging {
private(set) internal var managedCommands: [T]
init(_ commands: [T]) {
managedCommands = commands
}
func updateCommands(parameter: T.Parameter) {
}
}
let manager = CommandManager([CommandInt(), CommandInt()])
manager.updateCommands(parameter: 123)
technogen
(Gor Gyolchanyan)
3
There's more than one way to achieve the effect you're after. The best approach heavily depends on what exactly is the problem you're solving.
For instance, what is a CommandManaging supposed to be in charge of? What does it mean to update commands? Is a command expected to provide a custom interface that needs to be retained when necessary?