Using the where statement with protocols

With protocols, we are able to use the where statement to filter the instances of our types. For example, if we only want to get the instances that conform to the SeaAnimal protocol, we can create a for loop as follows:

for (index, animal) in animals.enumerated() where animal is SeaAnimal { 
  print("Only Sea Animal: (index)") 
} 

This will retrieve only the animals that conform to the SeaAnimal protocol. This is a lot safer than using flags as we did in the object-oriented design.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset