
Swift: Accomplishing Dynamic Dispatch on PATs (Protocol with Associated Types) - mpweiher
https://medium.com/@kahseng.lee123/accomplishing-dynamic-dispatch-on-pats-protocol-with-associated-types-b29d1242e939
======
skue
The problem with this is that any time you add a subclass to Animal, you need
to manually update AnyAnimal to handle it.

It’s possible to do this more generically, because you know the animal’s type
in the AnyAnimal constructor and that’s sufficient to declare its subsequent
behavior:

    
    
      struct AnyAnimal: Animal {
        let name: String
        private let walker: () -> Void
        private let eater: (Any) -> Void
        
        init<T: Animal>(_ animal: T) {
          name = animal.name
          walker = { animal.walk() }
          eater = { food in
            guard let f = food as? T.FoodType else { return }
            animal.eat(food: f)
          }
        }
        
        func walk(){ walker() }
        
        func eat(food: Any){ eater(food) }
      }

~~~
yeos_lee
Hi skue, thanks for this awesome suggestion. I will update the article to
include your suggestion. :)

