官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 怀来县| 舞钢市| 龙山县| 晋江市| 曲松县| 平度市| 乡城县| 时尚| 桐柏县| 锦屏县| 华阴市| 东丰县| 从化市| 梅州市| 攀枝花市| 社会| 怀安县| 金川县| 嵩明县| 长岛县| 资源县| 深圳市| 昔阳县| 新竹市| 三台县| 海伦市| 庆阳市| 开平市| 静安区| 广州市| 和静县| 额敏县| 河池市| 凤庆县| 连山| 逊克县| 甘谷县| 建阳市| 福海县| 班玛县| 乌兰浩特市|