December 2018
Intermediate to advanced
414 pages
10h 19m
English
There is a basic implementation of type erasure that is particularly suited if your protocols have few methods. This method is interesting as it requires very few elements, compared to the full erasure pattern. However, it achieves the same goal.
Let's go back to our animal example:
struct Grass: Food {}struct Cow: Animal { func eat(food: Grass) { print("Grass is yummy! moooooo!") }}struct Goat: Animal { func eat(food: Grass) { print("Grass is good! meehhhh!") }}
If you remember clearly, we wanted to keep all our grass-eating animals together; however, that wasn't possible:
let grassEaters: [Animal] = [Cow(), Goat()] // protocol 'Animal' can only be used as a generic constraint...let grassEaters: [Animal<Grass>] = ...
Read now
Unlock full access