The boxing-based type erasure pattern requires three distinct objects:
- An abstract base class
- A private box, which will inherit the abstract base class
- A public wrapper
As for the public wrapper, we can reuse the one that we wrote above AnyAnimal<T>.
In order to make the exercise a bit more interesting, let's change the Animal protocol to introduce some complexities such as the animal's preferred food and name:
protocol Animal {
associatedtype FoodType: Food
var preferredFood: FoodType? { get set }
var name: String { get }
func eat(food: FoodType)
}
Reflecting the changes in the Animal protocol, we need to update AnyAnimal. Let's not bother too much with the initializers now, as we'll implement them as we go:
final class AnyAnimal<T>: Animal where T: Food {
typealias FoodType = T
var preferredFood: T?
let name: String = ""
func eat(food: T) {}
}
Let's now go over the two new required components that will allow us to achieve the type erasure pattern fully.