O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required