Swift: Accomplishing Dynamic Dispatch on PATs (Protocol with Associated Types)
medium.com
medium.com
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) }
}