December 2018
Intermediate to advanced
414 pages
10h 19m
English
The boxing-based type erasure pattern requires three distinct objects:
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:
Read now
Unlock full access