iOS Programming Cookbook
上QQ阅读APP看书,第一时间看更新

Checking protocol conformance

It would be very useful to check whether an object conforms to a specific protocol or not. It's very useful when you have a list of objects, and only some of them conform to specific protocol. To check for protocol conformance, do the following:

class Rocket{ 
} 
 
var movingObjects = [Bicycle(name: "B1"), Car(name:"C1"), Rocket()] 
 
for item in movingObjects{ 
   if let vehicle =  item as? VehicleProtocol{ 
       print("Found vehcile with name \(vehicle.name)") 
       vehicle.move() 
   } 
   else{ 
       print("Not a vehcile") 
   } 
} 

We created a list of objects, and some of them conform to VehicleProtocol that we created earlier. Inside the for-loop we casted each item to VehicleProtocol inside if statement; the cast will succeed only if this item already conforms to that protocol.