您是否考虑过使用具有关联值的枚举(通常称为复杂枚举)
enum Directive {
case draw(NSRect)
case toggle(Bool)
}
struct Command {
let directive: Directive
}
let command = Command(directive: .draw(.zero))
let command2 = Command(directive: .toggle(true))
func processCommand(_ command: Command) {
switch command.directive {
case .draw(let rect):
// do something with rect
case .toggle(let value):
// do something with the value
}
}
(实际上,你可以跳过
Command
结构完全在上面)
或者,另一种解决方案是使用具有关联类型的协议:
protocol Command {
associatedtype AssociatedType
var argument: AssociatedType { get }
init(_ argument: AssociatedType)
func process()
}
struct DrawCommand: Command {
typealias AssociatedType = NSRect
let argument: AssociatedType
init(_ argument: AssociatedType) {
self.argument = argument
}
func process() {
print("draw something with \(argument)")
}
}
struct ToggleCommand: Command {
typealias AssociatedType = Bool
let argument: AssociatedType
init(_ argument: AssociatedType) {
self.argument = argument
}
func process() {
print("toggle something with \(argument)")
}
}
let command = DrawCommand(.zero)
let command2 = ToggleCommand(true)
command.process()
command2.process()