Challenge B: Pet shop tasks

Create a collection of protocols for tasks at a pet shop. The pet shop has dogs, cats, fish and birds.

The pet shop duties can be broken down into these tasks:

  • All pets need to be fed.
  • Pets that can fly need to be caged.
  • Pets that can swim need a tank.
  • Pets that walk need exercise.
  • Tanks and cages need to occasionally be cleaned.

  • Create classes or structs for each animal and adopt the appropriate protocols. Feel free to simply use a print() statement for the method implementations.

  • Create homogeneous arrays for animals that need to be fed, caged, cleaned, walked, and tanked. Add the appropriate animals to these arrays. The arrays should be declared using the protocol as the element type, for example var caged: [Cageable]
  • Write a loop that will perform the proper tasks (such as feed, cage, walk) on each element of each array.

The truth is, you already know about generics. Every time you use a Swift array, you’re using generics. This might even give the impression that generics are about collections, but that impression is both incorrect and misleading.

In this chapter, you’ll learn about the fundamentals of what generics are. This will give you a solid foundation for understanding how to write your own generic code. Finally, you’ll loop back to look at generic types in the Swift standard library: arrays, dictionaries and optionals—using this new perspective.

results matching ""

    No results matching ""