2016-10-30 1 views
1

Disons que j'ai ces protocoles:Puis-je faire une structure ou classe se conformer à un protocole générique plusieurs fois?

protocol Command {} 

protocol CommandHandler 
{ 
    associatedtype T: Command 
    func handle(command: T) throws 
} 

Je voudrais faire une commande gestionnaire qui peut gérer plusieurs commandes, comme ceci:

class InventoryCommandHandler: CommandHandler 
{ 
    func handle(command: AddItemCommand) { 
     // do something 
    } 

    func handle(command: RemoveItemCommand) { 
     // do something 
    } 

    func handle(command: SomeOtherCommand) { 
     // do something 
    } 
} 

Mais quand j'essaie qu'il dit que InventoryCommandHandler n'est pas conforme au protocole CommandHandler. Y a-t-il un moyen de le faire?

Répondre

2

Vous devriez défini CommandHandler comme ce

protocol CommandHandler { 
    func handle(command: Command) throws 
} 

Maintenant, étant donné ces 3 commandes

struct AddItemCommand: Command { } 
struct RemoveItemCommand: Command { } 
struct SomeOtherCommand: Command { } 

Vous pouvez créer votre InventoryCommandHandler

class InventoryCommandHandler: CommandHandler { 
    func handle(command: Command) throws { 
     switch command { 
     case let add as AddItemCommand: handle(command: add) 
     case let remove as RemoveItemCommand: handle(command: remove) 
     case let other as SomeOtherCommand: handle(command: other) 
     default: break 
     } 
    } 

    private func handle(command: AddItemCommand) { 
     // do something 
    } 

    private func handle(command: RemoveItemCommand) { 
     // do something 
    } 

    private func handle(command: SomeOtherCommand) { 
     // do something 
    } 
} 
1

La question en essayant de mettre en œuvre un Commande- gestionnaire qui peut gérer plusieurs commandes avec votre solution actuelle tion est

Votre protocole définit une fonction handle(command:) mais vous avez déclaré trois InventoryCommandHandler - ce jetterait une erreur même si vous enleviez votre erreur « conformité du protocole » courant parce que vous écrivez essentiellement la même méthode dans InvertoryCommandHandler trois fois. Même si AddItemCommand, RemoveItemCommand et SomeOtherCommand peuvent se conformer au même protocole (Command), il serait trop ambigu pour le compilateur de comprendre la différence car il considérerait tous les trois comme essentiellement la même fonction.

La méthode recommandée serait de définir une fonction pour chaque commande dans votre protocole InventoryCommandHandler.

protocol CommandHandler 
{ 
    func handle(command: AddItemCommand) throws 
    func handle(command: RemoveItemCommand) throws 
    func handle(command: SomeOtherCommand) throws 

    //add more as more commands made 
} 

Il existe de nombreuses solutions à votre problème et ce n'est qu'un exemple.