4 ms·
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 generica
by skue 9y ago
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 9y agoHi skue, thanks for this awesome suggestion. I will update the article to include your suggestion. :)